Microprocessors · Lecture Notes

Chapter 10.2: Device Control

A microprocessor reaches the outside world through the bytes it writes to peripherals and reads back from them. Lighting a traffic lamp, turning a motor by one step, and reading a temperature are the same job from the processor's point of view: write a number to a given port, or read a number from it. This note covers the two 8086 instructions that do this, IN and OUT, the I/O address space, and how the port number is written into the instruction. It then compares the three ways of waiting for a device to become ready (polling, interrupts, direct memory access). On the hardware side it treats the 8255 programmable peripheral interface, the unipolar stepper motor driver, and the 7-segment display. Programs that drive the seven virtual devices of emu8086 are traced line by line at register level: traffic lights, stepper motor, LED display, thermometer, printer, robot, and the I/O test device.

Learning outcomes

Port-based I/O
Explain the four forms of IN and OUT, how the port number is given (constant or in DX), and the rule that data passes only through AL or AX; compare port-mapped and memory-mapped I/O.
Bit-level control
Decode how each bit of a port corresponds to a lamp, a magnet, or a status flag; compute the byte or word that produces a desired behavior.
Polling
Write loops that wait for a device's ready or busy bit; compare the cost of polling with interrupts and direct memory access.
Timing
Compute the CX:DX wait time for INT 15h / AH = 86h; find the number of clock cycles and the duration of a software delay built with LOOP.
Real interface chips
Build the control word and the bit set/reset word of the 8255 PPI; drive a unipolar stepper motor through a ULN2003 and a 7-segment display by multiplexed scanning.
emu8086 devices
Read, single-step, and modify the programs that drive the traffic lights, stepper motor, LED display, thermometer, printer, robot, and test device.
Embedded-system view
Explain how a program is loaded from ROM into RAM and runs in an endless loop.

10.2.1I/O basics

10.2.1.1Peripherals, ports, and embedded systems

On its own, a microprocessor deals only with the numbers in its registers and memory. A lamp lighting up, a motor turning, or a key being pressed is the business of a circuit outside the processor. The circuits that attach to the processor and exchange data with it are called peripherals. A keyboard, a video card, a printer, a timer chip, an analog-to-digital converter, and a motor driver are all peripherals.

What a peripheral shows to the processor is one or more registers. One register holds the command or data going to the device. Another holds data coming from the device, and a third reports the device's status: ready, busy, or in error. Each of these registers is selected by an address. The gateway through which the processor reads and writes at these addresses is called an I/O port.

Definition 10.2.1

An I/O port is the address, as seen by the processor, of a register in a peripheral. On the 8086 a port is read with IN and written with OUT. Only the hardware attached to the port decides what a written value means: the same OUT instruction lights a lamp on one device and turns a motor on another.

Port numbers belong to the system, not to the processor. The 8086 only produces an address; the address decoder on the motherboard decides which device answers at that address. An address decoder is a gate circuit that looks at the bits on the address bus and enables a device only within its own address range. For this reason base port numbers can vary from system to system, and the same device can be moved to another port by a different decoder. On the IBM PC the keyboard controller sits at 60h and the interrupt controller at 20h–21h; the virtual traffic lights of emu8086 are at port 4. These numbers are the result of a hardware design, not a rule of the 8086.

The most typical home of programs that drive peripherals is the embedded system. A washing machine, a printer, a modem, and a traffic-light controller are built around a microprocessor or microcontroller. These devices often have no operating system or disk. The program is compiled on a development computer and converted to a plain binary file (.bin). The file is written to a ROM (read-only memory) chip. When the device powers up, the processor reads the program from ROM, copies it to RAM if necessary, and starts executing. Figure 10.2.1 shows these three steps.

ROMprogram.binRAMrunning copyCPUexecutesI/O ports① read② load③ IN / OUT
Figure 10.2.1: The path of a program in an embedded system. (1) At power-up the processor reads program.bin from ROM, (2) loads the running copy into RAM, (3) the program talks to the devices through I/O ports, with the IN and OUT instructions.

An embedded program has a shape of its own. A desktop program returns to the operating system when it finishes; an embedded program has nowhere to return to. It therefore begins with a setup part and then enters a loop that never ends. On every turn the loop reads the state of the devices, makes a decision, and writes new values to the devices. The traffic-light, stepper-motor, and thermostat programs have exactly this shape.

emu8086 imitates this world in software. Seven virtual devices attached to the 8086 emulator wait at specific port numbers (Table 10.2.1). The devices are opened from the virtual devices menu. If a directive such as #start=Traffic_Lights.exe# is written at the top of a program, the emulator opens the device window itself when the program starts. This line is not an 8086 instruction; it is only an instruction to the emulator and adds no bytes to the compiled code.

Table 10.2.1: Virtual devices attached to emu8086 and their ports.
DevicePort(s)DirectionData
Traffic lights4OUTword: 12 lamp bits
Stepper motor7OUT / INbits 0–2 magnets, bit 7 ready
Robot9, 10, 11OUT / INcommand, data, status
Test device (simple io test)110, 112IN / OUTbyte (110), word (112)
Thermometer and heater125, 127IN / OUTtemperature, heater on/off
Printer130OUTcharacter (via INT 21h/05h)
LED display199OUTword: signed number

All the port numbers in the table are less than 255. This detail looks small but it determines how the instruction is written: a port number in the range 0–255 can be written directly inside the instruction.

10.2.1.2The IN and OUT instructions

The 8086 has two instructions that access ports. IN reads from a port and writes the value read into the accumulator (AL or AX). OUT writes the value in the accumulator to a port. The port number is given in one of two ways: as an 8-bit constant inside the instruction if it lies between 0 and 255, and in the DX register otherwise. Table 10.2.2 lists all the forms.

Table 10.2.2: Forms of IN and OUT, their machine codes, and 8086 timings.
FormMeaningPort rangeMachine codeClock cycles
IN AL, portread 1 byte from the port0–255 (constant)E4 pp10
IN AX, portread 1 word from the port0–255 (constant)E5 pp10
IN AL, DX / IN AX, DXport number in DX0–65.535EC / ED8
OUT port, AL / OUT port, AXwrite to the port0–255 (constant)E6 pp / E7 pp10
OUT DX, AL / OUT DX, AXport number in DX0–65.535EE / EF8

The machine codes make the logic of the forms clear. The constant-port form is two bytes: the first byte is the opcode and the second is the port number (pp). For example IN AL, 7 assembles to E4 07, OUT 4, AX to E7 04, and IN AX, 112 to E5 70 (112 = 70h). Because only one byte is reserved for the port number, a number above 255 does not fit this form. The DX form is a single byte; the port number is in the register, not in the instruction. OUT DX, AL is just EE. The lowest opcode bit selects the data width: 0 means byte (AL), 1 means word (AX). That is why the pairs E4/E5, E6/E7, EC/ED, and EE/EF differ by 1.

CPUAL / AXI/O portn or [DX]OUT port, AL/AXIN AL/AX, port
Figure 10.2.2: The data path of IN and OUT. Data passes only through AL or AX; the port number is the constant n in the instruction, or DX.

Both instructions share one strict rule about the accumulator. Data passes only through AL (byte) or AX (word). OUT 4, BX and IN CL, 7 cannot be written; the 8086 has no such opcode. To send a value held in BX to a port, write MOV AX, BX first. The order of the operands is fixed as well: in OUT the port comes first and AL/AX second; in IN it is the reverse. The order follows the "destination, source" convention of MOV: the destination of OUT is the port, the destination of IN is the accumulator.

These instructions do not touch the flags. IN AL, 125 leaves SF unchanged even if the temperature read is negative; testing the value needs a CMP or TEST afterwards. The value read goes only into the accumulator, and no other register changes.

The word form uses two consecutive ports together. OUT 4, AX writes AL to port 4 and AH to port 5. IN AX, 112 takes AL from port 112 and AH from port 113. As with words in memory, the low byte is at the low address (little-endian). The 16-bit data bus of the 8086 transfers an even-addressed word in a single bus cycle. An odd-addressed word needs two separate byte transfers and takes 4 more clock cycles. This is one reason device registers are placed at even addresses.

The clock counts hold an interesting detail. According to Intel's manual the DX form takes 8 cycles, faster than the constant-port form (10 cycles), and it is one byte shorter. If DX is loaded once for a frequently accessed port and reused throughout a loop, every access saves two cycles.

Common mistake

Writing OUT 7, BL, IN BX, DX, or OUT AL, 7. The first two break the accumulator rule and the last breaks the operand order. The assembler rejects all three. The correct forms are MOV AL, BL · OUT 7, AL, IN AX, DX · MOV BX, AX, and OUT 7, AL.

10.2.1.3Port number: constant or in DX

The I/O address space of the 8086 is 16 bits wide: 65,536 byte ports from 0000h to FFFFh. The first 256 of them are reached with a constant inside the instruction. For the rest, the port number is first loaded into DX. For example, writing a byte to port 300 is done like this:

mov dx, 300     ; 300 = 012Ch > 255
mov al, 5Ah
out dx, al      ; port 012Ch ← 5Ah

The first instruction loads 012Ch into DX (BA 2C 01). The second puts the data to send into AL. The third is the single-byte EE; in the I/O bus cycle the processor puts DX on the address bus and AL on the data bus. Had you written OUT 300, AL, the assembler would reject it, because 300 does not fit in a byte.

The DX form is not only for large port numbers. It is also needed when the port number is computed while the program runs. For example, if the four registers of a board are at 310h, 311h, 312h, and 313h, the base address is loaded into DX and INC DX steps to the next register. With the constant-port form the port number is fixed at assembly time and cannot be changed.

All the virtual devices of emu8086 are below 255, so the programs that drive them use the constant-port form: OUT 4, AX, IN AL, 7, OUT 199, AX. Real boards such as the 8255 usually sit in the range 300h–31Fh on a PC and are driven through DX.

10.2.1.4Port-mapped and memory-mapped I/O

There are two ways to connect a device register to the processor. In the first, devices sit in an address space separate from memory and are reached only with special I/O instructions. This is called port-mapped I/O (also isolated I/O). In the second, device registers are placed in part of the memory address space and are read and written with ordinary memory instructions. This is called memory-mapped I/O.

Definition 10.2.2

In port-mapped I/O the devices are in a separate 64 K I/O address space; access is only through IN and OUT, and no memory addresses are used up. In memory-mapped I/O the device registers are inside the 1 MB memory space; any instruction with a memory operand, such as MOV, ADD, CMP, or AND, can access the device.

memory 00000h – FFFFFh (1 MB)I/O 0000h – FFFFhIN / OUT, M/IO̅ = 0B800hmemorydevice in memory: MOV, ADD, CMP … usableport-mappedmemory-mapped
Figure 10.2.3: The two address spaces of the 8086. On the left, the 1 MB memory (00000h–FFFFFh); the text screen memory in segment B800h is a memory-mapped device. On the right, the 64 K I/O space (0000h–FFFFh); only IN and OUT reach it.

The processor uses both spaces with the same address and data buses. A control signal says which one is being accessed: on the 8086 the M/IO̅ pin is 1 in a memory cycle and 0 in an I/O cycle. IN and OUT are the only instructions that drive this pin to 0. The clock-cycle-level detail of this signal, of the read and write pins, and of the bus cycle belongs to the 8086 pins. For the programmer the consequence is simple: port 4 and memory address 0000:0004 are two completely independent places.

The most familiar example of memory-mapped I/O is the PC's text screen. In 80×25 text mode each cell of the screen holds two bytes in memory starting at B800:0000: the character code and the attribute (color) byte. The video card turns a byte written there into an image at once. The following program writes a yellow "A" on a blue background in the top-left corner of the screen, with a "B" next to it:

org 100h
mov ax, 0B800h
mov es, ax              ; ES = text screen segment
mov di, 0               ; row 0, column 0
mov al, 'A'
mov ah, 1Eh             ; blue background, yellow text
mov es:[di], ax         ; character + attribute
mov byte ptr es:[di+2], 'B'
ret

The program has not a single I/O instruction, yet the screen changes. Because a constant cannot be loaded directly into a segment register, B800h goes into AX first and from there into ES. mov es:[di], ax writes two bytes with one instruction: 41h in AL goes to B800:0000 and 1Eh in AH goes to B800:0001. The physical address is B800h × 16 + 0 = B8000h. The last instruction writes only the character byte; the attribute of the second cell keeps its old value (07h, light gray on black). Table 10.2.3 is the trace of the program.

Table 10.2.3: Memory-mapped I/O: writing to the text screen with MOV.
StepInstructionAXESDIWritten to memoryExplanation
1mov ax, 0B800hB800h0700h0000hthe segment value goes through a general register first
2mov es, axB800hB800h0000hES = B800h: text screen memory
3mov di, 0B800hB800h0000hfirst cell: row 0, column 0
4mov al, 'A'B841hB800h0000hAL = 41h ('A')
5mov ah, 1Eh1E41hB800h0000hAH = 1Eh: blue background, yellow text
6mov es:[di], ax1E41hB800h0000hB800:0000 ← 41h, B800:0001 ← 1Ehone MOV: character and attribute; a colored A appears on the screen
7mov byte ptr es:[di+2], 'B'1E41hB800h0000hB800:0002 ← 42hcharacter byte of the second cell; the attribute (07h) is preserved
8ret1E41hB800h0000hthe program ends

The pros and cons of the two methods mirror each other (Table 10.2.4). With a memory-mapped device every memory instruction and every addressing mode can be used. For example INC BYTE PTR ES:[DI] increments a device register with one instruction, and TEST tests a device's status bit directly. On the other hand the device uses up memory addresses, and no memory can be placed at those addresses. A port-mapped device does not touch the memory space but is reached with only two instructions, only through AL/AX. To operate on a value read from it, the value must first be brought into the accumulator.

Table 10.2.4: Comparison of port-mapped and memory-mapped I/O.
FeaturePort-mappedMemory-mapped
Address spaceseparate, 64 K (0000h–FFFFh)shared with memory, part of the 1 MB
InstructionsIN, OUT onlyMOV, ADD, CMP, TEST, AND …
Data registerAL / AX onlyany register or a constant
Addressingconstant (0–255) or DXall memory addressing modes
Memory lostnonethe addresses the device occupies
8086 signalM/IO̅ = 0M/IO̅ = 1
Exampleemu8086 devices, 8255, 8259AB800h text screen, A000h graphics memory

The 8086 family supports both methods, and the PC uses them together. Devices with few, small control registers (keyboard controller, timer, interrupt controller) are at ports. Devices that need a large data area (screen memory) are in memory. In processors with no separate I/O instructions (for example ARM) all devices are memory-mapped.

Common mistake

Confusing a port number with a memory address. MOV AL, [4] reads the memory byte at DS:0004, not port 4; nothing happens to the traffic lights. A port-mapped device is reached only by IN and OUT.

10.2.1.5Polling, interrupts, and DMA

Devices are much slower than the processor. A stepper motor reaches its new position in milliseconds; in that time the 8086 executes thousands of instructions. While a printer prints a character or a robot takes a step, the processor has to wait before sending the next command. There are three ways to find out that a device is ready.

The simplest is polling. The processor reads the device's status register over and over in a loop. When the "ready" bit is 1 it leaves the loop and sends or receives the data. The stepper motor of emu8086 is a good example: bit 7 of the byte read from port 7 is 1 when the motor is ready.

wait: in   al, 7          ; read status
      test al, 10000000b  ; bit 7: ready?
      jz   wait           ; 0: read again

TEST computes the logical AND of AL with the mask but writes the result nowhere; it only sets the flags. If bit 7 is zero the result is zero and ZF = 1, so JZ jumps back to the top of the loop. If bit 7 is one, ZF = 0 and the loop ends. Three instructions build a wait loop that spins until the device is ready.

Definition 10.2.3

Polling is the processor waiting for a device to become ready by reading the device's status bit in a loop. Coordinating the data transfer between a device and the processor through ready and busy bits is called handshaking.

The advantage of polling is its simplicity: no extra hardware or interrupt routine is needed, and the flow of the program can be followed at a glance. Its drawback is that the processor can do nothing else while it waits. If the motor completes a step in 10 ms, a 4.77 MHz 8086 burns about 47,700 clock cycles in the empty loop. In an embedded system that drives a single device this is acceptable. It is not acceptable if a keyboard, a display, and a communication line must be watched at the same time.

The second way is the interrupt. When the device is ready it sends a request signal to the processor. The processor finishes the current instruction, pushes the flags and the return address onto the stack, runs the device's service routine, and returns to where it left off with IRET. On the PC the requests of the devices are collected in the 8259A interrupt controller and passed to the processor by priority. With interrupts the processor does not wait, but it still moves the data itself: the IN and OUT instructions in the service routine are executed by the processor.

The third way is direct memory access (DMA). If a block of thousands of bytes is to be moved from disk to memory, even one interrupt per byte is too expensive. In that case a DMA controller such as the 8237 asks the processor for the bus, and once it gets the bus it moves the data between device and memory by itself, then hands the bus back when done. During the transfer the processor merely cannot use the bus; it can carry on with work in its internal registers.

Table 10.2.5: Three ways of coordinating with a device.
MethodWho waits?Who moves the data?Suited to
Pollingthe processor, in a loopthe processor (IN/OUT)a single device, simple embedded system
Interruptnobody; the device signalsthe processor (in the service routine)keyboard, serial line, timer
DMAnobody; the controller takes the busDMA controller (8237)block transfers such as disk and sound card

None of the virtual devices of emu8086 generates interrupts. All the programs in this note therefore use polling. The common pattern of a polling loop repeats for every device: read the status, test the relevant bit, write or read the data if ready, otherwise read again.

Common mistake

Using AND instead of TEST in a polling loop and then trying to use the data in AL. AND AL, 80h tests the status but clears the other bits of AL. If the status byte carries other information from the device (an error bit, a data bit), it is lost. TEST performs the same test without changing AL.

10.2.2The 8255 programmable peripheral interface

10.2.2.1Structure and address selection

The devices of emu8086 interpret the value written to a port themselves. On a real board, an interface chip stands between the processor and the lamp, switch, or motor driver. The most common parallel interface chip in 8086 systems is the Intel 8255. Its name is programmable peripheral interface (PPI). "Programmable" refers to the fact that software chooses whether its ports are inputs or outputs.

The 8255 has three 8-bit ports: A, B, and C. Port C can be split into two 4-bit halves: the upper half PC7–PC4 and the lower half PC3–PC0. Besides these there is a control register. The A1 and A0 pins of the chip select which of the four registers is accessed. Whether the chip is active at all is decided by the C̅S̅ (chip select) pin, which comes from the address decoder. Reading and writing are done with the processor's I/O read and I/O write signals (IOR̅, IOW̅). Figure 10.2.4 shows the connection.

8255D0–D7A0A1R̅D̅ (IOR̅)W̅R̅ (IOW̅)RESETaddress decoderC̅S̅PA0–PA7PB0–PB7PC4–PC7PC0–PC3port Aport Bport C upperport C lower
Figure 10.2.4: The processor side (D0–D7, A0, A1, R̅D̅, W̅R̅, RESET, C̅S̅) and the device side (PA0–PA7, PB0–PB7, PC7–PC4, PC3–PC0) of the 8255 PPI.

If the base address of the board is 310h, the addresses of the four registers are as in Table 10.2.6. The address decoder recognizes the range 310h–313h and drives C̅S̅ to 0; the lowest two address bits go to the A1 and A0 pins of the chip.

Table 10.2.6: Registers of the 8255 (base address 310h, A1 ← A1, A0 ← A0 wiring).
A1 A0RegisterAddress
0 0port A310h
0 1port B311h
1 0port C312h
1 1control register313h

This consecutive address layout is correct for the 8088, which has an 8-bit data bus. The data bus of the 8086 is 16 bits wide and is divided into two banks: even-addressed bytes are transferred on D0–D7 (the low bank) and odd-addressed bytes on D8–D15 (the high bank). The 8255 has only eight data pins. If the chip is wired to D0–D7, only its registers at even addresses can be reached. The solution is to connect the chip's A0 pin to the processor's A1 and its A1 pin to A2. The four registers then fall at 310h, 312h, 314h, and 316h, always at even addresses. The programs in this note use the consecutive layout 310h–313h; on a board built for the 8086 the addresses are changed accordingly.

All the addresses are above 255. Every access to the 8255 is therefore made through DX: MOV DX, 313h · OUT DX, AL. After RESET all ports of the 8255 are inputs. There is a safety reason for this: at power-up a chip that has not been programmed yet must not drive the connected circuit at random. The program therefore writes a control word to the control register before using the chip.

10.2.2.2Control word: mode selection

The highest bit (D7) of the byte written to the control register determines the kind of byte. If D7 = 1 the byte is a mode set word: it sets the mode and direction of the ports in one go. If D7 = 0 the byte is a bit set/reset word and changes only a single bit of port C.

Table 10.2.7: The 8255 mode set word (D7 = 1). In the direction bits, 1 = input, 0 = output.
D7D6 D5D4D3D2D1D0
1 = mode setgroup A mode (00 = mode 0)port APC7–PC4group B mode (0 = mode 0)port BPC3–PC0

The ports of the 8255 are divided into two groups. Group A is port A plus the upper half of C; group B is port B plus the lower half of C. Mode 0 is simple I/O without handshaking: a value written to a port stays on the output pins, and a value read from an input is the current state of the pins. Modes 1 and 2 are for handshaking transfers. In these modes some pins of port C are used as "data ready" (strobe) and acknowledge signals; mode 2 makes port A bidirectional. For lamps, switches, and motor drivers mode 0 is enough.

Example 10.2.1

Required: port A output (drives LEDs or relays), port B input (switches are read), both halves of C output, all in mode 0.

  1. D7 = 1: this is a mode set word.
  2. D6 D5 = 00 and D2 = 0: both groups in mode 0.
  3. D4 = 0 (A output), D3 = 0 (C upper output), D1 = 1 (B input), D0 = 0 (C lower output).
  4. Writing the bits side by side: 1 00 0 0 0 1 0b = 1000 0010b = 82h.

In the same way, A input, B output, and all of C input gives 1 00 1 1 0 0 1b = 99h; A output, B output, and all of C input gives 1 00 0 1 0 0 1b = 89h. If all ports are outputs the word is 1000 0000b = 80h.

The point that is most often confused when building the word is the meaning of the direction bits. In the 8255, 1 means "input" and 0 means "output". This is the opposite of the "1 = on" intuition and has to be memorized. The interactive control-word builder in the slides shows how the bits change as you click each port's direction; you can also type a value directly into the word box and read off the port directions.

10.2.2.3Bit set/reset (BSR)

Port C is often used as individual control pins: one pin drives a relay coil, another an LED, a third a digit-select transistor. Writing the whole port just to change one pin would mean keeping the values of the other pins separately in the program. The 8255 offers the bit set/reset (BSR) word instead.

Definition 10.2.4

The bit set/reset word is a control byte with D7 = 0. D3–D1 give the number (0–7) of the C bit to change and D0 gives the new value of that bit; D6–D4 are unused (write 0). The word is written to the control register, not to port C. The other C bits and the port directions do not change.

To set PC7 to 1, the bit number is 7 = 111b and the value is 1: 0000 1111b = 0Fh. To clear PC7 to 0 only D0 changes: 0000 1110b = 0Eh. In the same way the word that sets PC3 to 1 is 0000 0111b = 07h, and the word that clears PC0 to 0 is 00h. The last one is interesting: although 00h looks like a mode word, D7 = 0 makes it mean "PC0 = 0".

Common mistake

Writing a BSR word to port C (312h). The 0Fh written to port C sets PC3–PC0 to 1 and PC7–PC4 to 0: all eight bits are rewritten. A bit set/reset word is interpreted as a single-bit word only when it is written to the control register (313h).

10.2.2.4Code trace: setting up the 8255

The following program does four basic jobs in a row: it programs the chip with 82h, reads the switches on port B, writes the value read to the LEDs on port A, and sets PC7 to 1 with BSR.

org 100h
mov dx, 313h   ; control register
mov al, 82h    ; A,C out; B in
out dx, al
mov dx, 311h   ; port B
in  al, dx     ; read switches
mov dx, 310h   ; port A
out dx, al     ; drive the LEDs
mov dx, 313h
mov al, 0Fh    ; BSR: PC7 = 1
out dx, al
ret

Every I/O access of the program consists of the same two steps: first the address into DX, then IN or OUT. The switches wired to port B are assumed to be in the position 1001 0110b = 96h. Table 10.2.8 gives the trace, with each I/O operation in the last column.

Table 10.2.8: Trace of the 8255 setup program (switches on port B at 96h; each row shows the state after the instruction executes).
StepInstructionDXALI/OExplanation
1mov dx, 313h0313h00hDX = 313h: the address of the control register; kept in DX because it is above 255
2mov al, 82h0313h82hAL = 82h = 1000 0010b: mode 0; A output, C upper output, B input, C lower output
3out dx, al0313h82h313h ← 82hthe control word has been written to the chip; the port directions now follow 82h
4mov dx, 311h0311h82hDX = 311h: port B
5in al, dx0311h96h311h → 96hswitches read: AL = 96h = 1001 0110b
6mov dx, 310h0310h96hDX = 310h: port A
7out dx, al0310h96h310h ← 96hthe LEDs copy the switches: bits 7, 4, 2, and 1 light up
8mov dx, 313h0313h96hDX points to the control register again
9mov al, 0Fh0313h0FhAL = 0Fh = 0000 1111b: D7 = 0, so this is a bit set/reset word
10out dx, al0313h0Fh313h ← 0FhD3–D1 = 111 (PC7), D0 = 1: only PC7 becomes 1; the directions do not change
11ret0313h0Fh0000h popped from the stack → IP; returns to the INT 20h in the PSP
12INT 20h (PSP:0000)0313h0Fhthe program ends

Three details stand out in the trace. First, the OUT DX, AL instructions change no register; their effect is only inside the chip. Second, IN AL, DX wipes out the old value of AL (82h) completely. Third, although the last OUT writes to the control register, it does not change the port directions: because D7 = 0 the chip interprets it as a bit set/reset word. After the setup, bits 7, 4, 2, and 1 of the port A LEDs are lit, and in port C only PC7 = 1.

The machine code of the program is 21 bytes. The four MOV DX instructions take three bytes each, the two MOV AL instructions two bytes each, and the four I/O instructions and RET one byte each. This brevity is another benefit of the DX form: the port number is given in a single MOV, and the I/O instruction itself shrinks to one byte.

10.2.3Traffic lights

10.2.3.1Port 4 and the lamp bits

The traffic-light device of emu8086 is a four-way intersection. There is a pole at each corner and three lamps on each pole: red, yellow, and green. Each of the twelve lamps is wired to one bit of the 16-bit word written to port 4. A bit of 1 lights the lamp and 0 turns it off. Bits 12–15 are unused. Writing one word to port 4 therefore draws a complete snapshot of the intersection in one go.

The bits are distributed over the lamps in a regular way. If the poles are numbered k = 0, 1, 2, 3, then pole k has its red lamp at bit 3k, yellow at bit 3k + 1, and green at bit 3k + 2. The lower-right pole uses bits 0–2, the upper-right 3–5, the upper-left 6–8, and the lower-left 9–11 (hex 9, A, B).

0123456789ABFEDC BA98 7654 32100000 0011 0000 1100
Figure 10.2.5: Port 4 = 030Ch = 0000 0011 0000 1100b. The bits that are on are 2 and 8 (green), 3 and 9 (red): lower right and upper left are green, upper right and lower left are red.

To decode the value in Figure 10.2.5, split the word into groups of four: 0000 0011 0000 1100b. The bits that are 1, counted from the right, are bits 2, 3, 8, and 9. Bit 2 = 3 · 0 + 2, so it is the green of the lower-right pole. Bit 3 = 3 · 1 + 0 is the red of the upper-right pole. Bit 8 = 3 · 2 + 2 is the green of the upper-left pole, and bit 9 = 3 · 3 + 0 is the red of the lower-left pole. The reverse is just as easy: find the bit numbers of the lamps you want and add these powers of 2.

Example 10.2.2

What word lights only the green lamps in all directions?

  1. The green lamps are at bits 3k + 2: for k = 0, 1, 2, 3 that is bits 2, 5, 8, 11.
  2. The word is 2² + 2⁵ + 2⁸ + 2¹¹ = 4 + 32 + 256 + 2048 = 2340.
  3. In binary it is 0000 1001 0010 0100b, in hexadecimal 0924h.

Such a state is of course dangerous at a real intersection; the example only shows the bit arithmetic. The word that lights all the reds comes out the same way from bits 0, 3, 6, 9: 0000 0010 0100 1001b = 0249h. In the program this value is named all_red.

10.2.3.2State table

The operation of the intersection is a repetition of a few states in a fixed order. Each state is defined by a word to be written to port 4. The program keeps these words in memory as a consecutive table:

;                 FEDC_BA98_7654_3210
situation  dw     0000_0011_0000_1100b
s1         dw     0000_0110_1001_1010b
s2         dw     0000_1000_0110_0001b
s3         dw     0000_1000_0110_0001b
s4         dw     0000_0100_1101_0011b
sit_end = $
all_red    equ    0000_0010_0100_1001b

The underscores inside the numbers are only for readability; emu8086 ignores them. The sequence FEDC_BA98_7654_3210 in the comment line shows which bit each column is. The line sit_end = $ takes up no memory: $ is the assembler's current location counter and gives the address where the table ends. The program uses this address to answer the question "have I reached the end of the table?". all_red is a constant defined with EQU; it lives inside the instruction, not in memory.

Table 10.2.9: Traffic states and the lamps that are lit.
AdHexLower rightUpper rightUpper leftLower left
situation030Chgreenredgreenred
s1069Ahyellowred + yellowyellowred + yellow
s20861hredgreenredgreen
s30861hredgreenredgreen
s404D3hred + yellowyellowred + yellowyellow
all_red0249hredredredred

Every row of the table can be verified by bit arithmetic. In s1 = 069Ah = 0000 0110 1001 1010b the bits that are 1 are 1, 3, 4, 7, 9, and 10. Bit 1 is the yellow of the lower-right pole, bits 3 and 4 are the red and yellow of the upper-right pole, bit 7 is the yellow of the upper-left pole, and bits 9 and 10 are the red and yellow of the lower-left pole. In s1 the directions that are about to go from green to red show yellow, and the directions that are about to go from red to green show the "red + yellow" warning. Red + yellow is the transition signal that means "get ready". s4 makes the same transition in the opposite direction.

s2 and s3 are the same word. Because the program waits the same time (5 seconds) in every state, the green of the side road lasts two intervals, that is 10 seconds. To change the duration there is no need to touch the program; writing the same word once more in the table is enough. That the behavior lives in the table and not in the code is the greatest strength of this design.

0123456789ABFEDC BA98 7654 32100000 0010 0100 1001 0123456789ABFEDC BA98 7654 32100000 0011 0000 1100 0123456789ABFEDC BA98 7654 32100000 0110 1001 1010 0123456789ABFEDC BA98 7654 32100000 1000 0110 0001 0123456789ABFEDC BA98 7654 32100000 0100 1101 0011
Figure 10.2.6: The states the program writes to the intersection in turn: all_red (0249h), situation (030Ch), s1 (069Ah), s2 = s3 (0861h), and s4 (04D3h). Below each is the binary form of the word written to port 4.

The interactive traffic bit editor in the slides does the same calculation in the other direction: clicking a bit turns that lamp on or off and updates the hexadecimal value of the word. Clicking a name in the table loads the word of that state.

10.2.3.3Waiting with INT 15h

Every state must last a few seconds, so the program has to measure this time. The PC BIOS offers a ready-made service for it: INT 15h, AH = 86h. The service waits as many microseconds as the 32-bit number in the CX:DX pair. CX carries the high word and DX the low word.

Example 10.2.3

What must CX and DX be for a 5-second wait?

  1. Convert the time to microseconds: 5 s = 5 × 1,000,000 = 5,000,000 µs.
  2. Convert the decimal number to hexadecimal by repeated division by 16: 5,000,000 ÷ 16 = 312,500 remainder 0; 312,500 ÷ 16 = 19,531 remainder 4; 19,531 ÷ 16 = 1,220 remainder 11 (B); 1,220 ÷ 16 = 76 remainder 4; 76 ÷ 16 = 4 remainder 12 (C); 4 ÷ 16 = 0 remainder 4.
  3. The remainders are read from last to first: 4C4B40h. Written in 32 bits it is 004C4B40h.
  4. Split the number in two: CX = 004Ch, DX = 4B40h.
5,000,000 µs = 004C4B40h (32 bits)004C4B40CX = 004ChDX = 4B40hhigh wordlow word
Figure 10.2.7: 5,000,000 µs = 004C4B40h. The high word goes into CX (004Ch) and the low word into DX (4B40h).
; wait 5 seconds (5 million µs)
mov cx, 4Ch     ; 004C4B40h = 5 000 000
mov dx, 4B40h
mov ah, 86h
int 15h

The same calculation works for other durations. 1 second is 1,000,000 = 000F4240h: CX = 000Fh, DX = 4240h. 0.2 second is 200,000 = 00030D40h: CX = 0003h, DX = 0D40h. In the second example the hexadecimal value of DX starts with a letter; in the source code it is written 0D40h, because without the leading 0 the assembler would take it for a label name. The longest time the service can wait in one call is CX = DX = FFFFh, that is 4,294,967,295 µs: about 71.6 minutes.

After a successful wait CF = 0 is returned. In emu8086 the service leaves AX alone, whereas some real BIOSes write a status code into AH. The program therefore does not rely on the value in AX after the call. On a real PC this service is timed by the interrupt of the timer chip, and its duration does not depend on the speed of the processor. In emu8086 too, timed waiting is done with this service; the emulator applies the wait according to its own clock.

Common mistake

Splitting the time between CX and DX in decimal: writing CX = 5, DX = 0 for 5,000,000. CX:DX is a single 32-bit binary number; the value CX = 5, DX = 0 is 5 × 65,536 = 327,680 µs, about 0.33 second. The number is first converted to hexadecimal as a whole and then split into two 16-bit halves.

10.2.3.4Software delay: LOOP and clock cycles

In an embedded system that has no BIOS service, waiting is done by having the processor burn a known number of clock cycles. The simplest way is an empty LOOP loop. The duration of the loop is computed from the clock-cycle counts of the instructions. According to the 8086 manual the required timings are in Table 10.2.10.

Table 10.2.10: 8086 timings of the instructions in a delay loop.
InstructionClock cycles
MOV CX, constant4
LOOP (CX ≠ 0, jumps)17
LOOP (CX = 0, falls through)5
DEC r162
JNZ (taken / not taken)16 / 4
CALL near / RET near19 / 8
; ≈ 1 ms delay (4.77 MHz 8086)
mov  cx, 281    ; 4 clocks
delay:
loop delay      ; 280 × 17 + 1 × 5 clocks

In a loop that starts with CX = N, LOOP executes N times. In the first N − 1 times CX has not reached zero and the instruction jumps (17 cycles). The last time CX becomes 0 and the instruction falls through (5 cycles). The total time is:

T = 4 + 17(N − 1) + 5 = 17N − 8 clock cycles.

Converting clock cycles to time needs the frequency. The 8088 of the original IBM PC runs at 4.77 MHz: one clock cycle is 1 / 4.77 MHz ≈ 0.2096 µs. 1 ms is therefore 4,770 clock cycles. The equation 17N − 8 = 4,770 gives N ≈ 281.06. Since only an integer can be written into CX, the nearest value is chosen: N = 281, 17 · 281 − 8 = 4,769 cycles, that is ≈ 0.9998 ms.

The same loop gives a different time on another processor. At 5 MHz, 1 ms is 5,000 cycles; N ≈ 294.6, and choosing N = 295 gives 5,007 cycles ≈ 1.0014 ms. The N = 281 found for 4.77 MHz takes only 4,769 / 5 ≈ 954 µs at 5 MHz. This is the greatest flaw of software delays: the time depends on the clock speed. When the program is moved to a faster processor, all the waits get shorter.

A single loop also has an upper limit. A LOOP that starts with CX = 0 first brings CX down to FFFFh and runs 65,536 times. That is 17 · 65,536 − 8 = 1,114,104 cycles, about 233.6 ms at 4.77 MHz. A longer wait needs nested loops:

       mov  dx, 100     ; 4 clocks
outer: mov  cx, 281     ; 4 clocks
inner: loop inner       ; 17 · 280 + 5 = 4,765 clocks
       dec  dx          ; 2 clocks
       jnz  outer       ; 16 clocks, 4 on the last pass

One pass of the outer loop is 4 + 4,765 + 2 = 4,771 cycles, followed by a JNZ. In 99 of the hundred passes JNZ jumps (16), and in the last one it does not (4). The total is 4 + 100 · 4,771 + 99 · 16 + 4 = 478,692 cycles, about 100.4 ms at 4.77 MHz. The inner counter is in CX and the outer counter in DX; since LOOP uses only CX, the two counters do not interfere. If the delay is written as a procedure and called, each call also adds the CALL (19) and RET (8) cycles.

These calculations are approximate. Interrupts can slip in between the loop's instructions and lengthen the time. The wait states added by slow memory and the fullness of the instruction queue also change the cycle count. emu8086 does not model instruction timings: the loop runs at the speed of the computer and according to the emulator's step delay setting. That is why timed waiting in emu8086 is done with INT 15h/86h; the software delay calculation is for real hardware.

10.2.3.5Code trace: the delay loop

To see where the formula comes from, trace a short loop with CX = 4:

org 100h
mov cx, 4      ; 4 clocks
delay:
loop delay     ; 17 clocks, last one 5
ret
Table 10.2.11: Trace of the delay loop; the cycle totals in the explanation are computed from the 8086 instruction timings.
StepInstructionCXIPExplanation
1mov cx, 40004h0103h4 cycles; total 4
2loop delay0003h0103hCX = 3 ≠ 0: jumps to the same instruction, 17 cycles; total 21
3loop delay0002h0103hCX = 2: 17 cycles; total 38
4loop delay0001h0103hCX = 1: 17 cycles; total 55
5loop delay0000h0105hCX = 0: falls through, 5 cycles; total 60 = 17 · 4 − 8
6ret0000h0000hleft the loop; 60 cycles ≈ 12.6 µs at 4.77 MHz

The LOOP delay instruction jumps to its own address (0103h); its machine code is E2 FE, and FEh = −2 means going back by the length of the instruction itself. In the first three executions IP is again 0103h. On the fourth execution CX drops to 0, there is no jump, and IP moves on to 0105h, the RET. The total is 4 + 17 + 17 + 17 + 5 = 60 = 17 · 4 − 8 cycles. 60 cycles take 60 × 0.2096 ≈ 12.6 µs at 4.77 MHz.

10.2.3.6The traffic program

The program consists of four parts: the setup that turns all directions red, the loop body that writes the table word to the port, the 5-second wait, and the return to the start at the end of the table.

#start=Traffic_Lights.exe#
mov ax, all_red
out 4, ax
mov si, offset situation
next:
mov ax, [si]
out 4, ax
mov cx, 4Ch      ; wait 5 s
mov dx, 4B40h
mov ah, 86h
int 15h
add si, 2        ; next state
cmp si, sit_end
jb  next
mov si, offset situation
jmp next
; the state table follows (situation … all_red)

The first thing the program does is turn all directions red. This is a safety measure: when the controller powers up, it is not known what state the intersection was left in, and green must never be shown to one direction while another has green. MOV AX, all_red loads the constant directly into AX (B8 49 02); OUT 4, AX writes the two bytes of the word to ports 4 and 5.

SI holds the address of the next word in the table. MOV AX, [SI] reads the word at that address, and OUT 4, AX switches the intersection to that state. Then the program waits 5 seconds. ADD SI, 2 moves to the next word; since the table consists of words, the step is 2 bytes. CMP SI, sit_end compares SI with the end address of the table. If SI is still smaller, CF = 1 and JB next goes back to the loop. When they are equal, CF = 0; SI is set back to the start of the table and JMP next restarts the loop. The program never ends: in embedded systems the main program is usually an endless loop like this.

The location of the table in memory depends on the length of the code. If the program is assembled with ORG 100h, the code takes 36 bytes and the table starts at 0124h: situation is at 0124h, s1 at 0126h, s2 at 0128h, s3 at 012Ah, and s4 at 012Ch; sit_end = 012Eh. If the table's place in the source changes, these addresses change too, but the program keeps working correctly because it uses only labels. When emu8086 loads a .COM program it loads the program size into CX; the trace takes CX before the first MOV CX as 0000h. Since the program does not rely on this initial value, the result is unchanged.

Table 10.2.12: Trace of the traffic-light program (table at 0124h; except for the INT 15h wait, each row shows the state after the instruction executes).
StepInstructionAXSICXDXCFPort 4Explanation
1mov ax, all_red0249h0000h0000h0000h0—AX = all_red = 0249h; an EQU constant, takes up no memory
2out 4, ax0249h0000h0000h0000h00249hall directions red
3mov si, offset situation0249h0124h0000h0000h00249hSI = 0124h: the first word of the table (situation)
4mov ax, [si]030Ch0124h0000h0000h00249hAX ← [0124h] = 030Ch
5out 4, ax030Ch0124h0000h0000h0030Chthe lamps switch to the situation state
6mov cx, 4Ch030Ch0124h004Ch0000h0030ChCX = 004Ch: the high word of 5,000,000 µs
7mov dx, 4B40h030Ch0124h004Ch4B40h0030ChDX = 4B40h: the low word
8mov ah, 86h860Ch0124h004Ch4B40h0030ChAH = 86h: the BIOS wait service; AL is unchanged
9int 15h860Ch0124h004Ch4B40h0030Chwaits 5 seconds; CF = 0 on success
10add si, 2860Ch0126h004Ch4B40h0030ChSI = 0126h: next state
11cmp si, sit_end860Ch0126h004Ch4B40h1030Ch0126h − 012Eh: borrow, CF = 1
12jb next860Ch0126h004Ch4B40h1030ChJB jumps: next
13mov ax, [si]069Ah0126h004Ch4B40h1030ChAX ← [0126h] = 069Ah (s1)
14out 4, ax069Ah0126h004Ch4B40h1069Ahyellow transition state
…wait, SI = 0128h, CMP and JB
23out 4, ax0861h0128h004Ch4B40h10861hs2 = 0861h; side road green
…wait, SI = 012Ah
32out 4, ax0861h012Ah004Ch4B40h10861hs3 = 0861h; the same state lasts another 5 seconds
…wait, SI = 012Ch
41out 4, ax04D3h012Ch004Ch4B40h104D3hs4 = 04D3h; getting ready to return to the main road
…wait
46add si, 286D3h012Eh004Ch4B40h004D3hSI = 012Eh = sit_end
47cmp si, sit_end86D3h012Eh004Ch4B40h004D3hequal: CF = 0, ZF = 1
48jb next86D3h012Eh004Ch4B40h004D3hJB falls through: the table is finished
49mov si, offset situation86D3h0124h004Ch4B40h004D3hSI goes back to the start of the table
50jmp next86D3h0124h004Ch4B40h004D3hendless loop
51mov ax, [si]030Ch0124h004Ch4B40h004D3hAX ← [0124h] = 030Ch
52out 4, ax030Ch0124h004Ch4B40h0030Chsituation again: the loop starts over

The trace also shows that the INT 15h call leaves a mark in AX. MOV AH, 86h changes only the upper byte; AL keeps the low byte of the last state read. That is why AX = 860Ch after step 8. Because MOV AX, [SI] at the top of the loop rewrites the whole of AX, this is no longer a problem.

Common mistake

Writing INC SI instead of ADD SI, 2. The table consists of words; if SI is incremented by one, the second read starts in the middle of a word. The word read from 0125h is 9A03h, the combination of the high byte of situation (03h) and the low byte of s1 (9Ah). This value lights a meaningless lamp pattern that also spills into bits 12–15.

10.2.4Stepper motor

10.2.4.1The emu8086 stepper motor

An ordinary DC motor turns for as long as voltage is applied; to know how far it has turned you need a separate sensor. A stepper motor, on the other hand, turns through a fixed angle with each new excitation pattern applied to its windings, and stops there. The shaft takes the position given by which windings carry current. If the excitation pattern is changed in sequence, the motor turns step by step. Its position is therefore known from the number of steps sent. Printer heads, floppy-disk drives, 3D printers, and CNC machines are driven by stepper motors.

The stepper motor of emu8086 is attached to port 7 and is a simplified model. Bits 0, 1, and 2 of the byte written to the port switch three electromagnets on or off. The motor can be turned both clockwise (CW) and counterclockwise (CCW). A half step is 11.25° and a full step is 22.5°; a full revolution is therefore 32 half steps or 16 full steps.

2107654321000000110port 7 = 00000110b
Figure 10.2.8: The emu8086 stepper motor. Port 7 = 0000 0110b: the magnets wired to bit 2 and bit 1 are on, and the rotor is pulled between the two.

The motor also has a status output. After an OUT instruction the motor is busy until it reaches its new position. When it is ready to accept a new command it makes bit 7 of the byte read from port 7 equal to 1. The program polls this bit before sending each byte. A byte sent to a motor that is not ready is lost, or the motor skips a step.

10.2.4.2Data tables and magnet patterns

Turning the motor means switching the magnets on and off in a particular order. In the program this order is kept as four-byte tables. The sample program of emu8086 defines four tables (Table 10.2.13).

Table 10.2.13: Stepper motor data tables (bits 2–0 = magnets 2–0; addresses for ORG 100h).
TableAddressMeaning1234
datcw0102hCW half step110100011010
datccw0106hCCW half step011001110010
datcw_fs010AhCW full step001011110000
datccw_fs010EhCCW full step100110011000

Each bit of the byte stands for one magnet: 110b means magnets 2 and 1 are on and 0 is off; 000b turns all the magnets off. The half-step table turns on two magnets and one magnet alternately: 110 (two), 100 (one), 011 (two), 010 (one). With two magnets on the rotor rests between them, and with one magnet on it rests facing that magnet. These intermediate positions halve the step. The full-step table sends the bytes single, double, double magnet, and "all off".

110100011010011001110010001011110000100110011000datcw · 0102hdatccw · 0106hdatcw_fs · 010Ahdatccw_fs · 010Ehadd bx, 4 → next table
Figure 10.2.9: The four tables lie back to back in memory and each is 4 bytes. Adding 4 to BX moves to the next table.

That the tables are consecutive in memory is the most useful detail of the program. datcw starts at 0102h; datccw is 4 bytes later, at 0106h; datcw_fs is at 010Ah; datccw_fs is at 010Eh. If BX points to the start of one table, ADD BX, 4 moves it to the next. After 32 (20h) rounds the program changes the table. The direction and step type thus cycle in the order CW half → CCW half → CW full → CCW full → back to the start.

The notation in the source code can vary as well. In the original emu8086 sample each byte is on a separate line and written with eight digits: datcw db 0000_0110b, on the next line db 0000_0100b … In this note's program the table is squeezed onto one line with the same values: datcw db 110b,100b,011b,010b. Both notations produce the same four bytes.

2107654321000000110datcw[0] = 110b 2107654321000000100datcw[1] = 100b 2107654321000000011datcw[2] = 011b 2107654321000000010datcw[3] = 010b
Figure 10.2.10: The four bytes of the datcw table in turn: 110b (magnets 2 and 1), 100b (2), 011b (1 and 0), 010b (1). Each byte turns the rotor by one half step, 11.25°.

10.2.4.3The control program

ORG 100h
steps_before_direction_change = 20h
jmp start
datcw     db 110b,100b,011b,010b
datccw    db 011b,001b,110b,010b
datcw_fs  db 001b,011b,110b,000b
datccw_fs db 100b,110b,011b,000b
start:
mov bx, offset datcw
mov si, 0
mov cx, 0              ; round counter
next_step:
wait: in   al, 7
      test al, 10000000b
      jz   wait
mov al, [bx][si]
out 7, al
inc si
cmp si, 4
jb  next_step
mov si, 0
inc cx
cmp cx, steps_before_direction_change
jb  next_step
mov cx, 0
add bx, 4              ; next table
cmp bx, offset datccw_fs
jbe next_step
mov bx, offset datcw
jmp next_step

steps_before_direction_change = 20h is a constant. The = directive works like EQU: it takes up no memory and is replaced by its value wherever it is used. Because the tables sit at the start of the code, the first instruction JMP start jumps over them; otherwise the processor would take the table bytes for instructions and execute them. The code of the short jump is EB 10: 16 bytes forward from 0102h, to 0112h.

The program has three counters. BX holds the start of the table in use, SI the position within the table (0–3), and CX the number of completed rounds. The first three lines of the loop body are the polling loop: while bit 7 = 0 the motor is busy and the port is read again. When bit 7 = 1, MOV AL, [BX][SI] reads the next byte.

The notation [BX][SI] is the same as [BX + SI]: base plus index addressing. BX gives the start address of the table and SI the position in that table; the effective address is the sum of the two. For BX = 0102h and SI = 2 the byte read is [0104h] = 011b. This addressing mode can be thought of as the row and column of a two-dimensional array: BX says which table, SI which element of the table.

After the byte is written to the port, SI is incremented. If SI is less than 4, the next byte of the same table is used. When SI = 4 the table is finished: SI is reset and CX is incremented. If CX has not yet reached 20h, the same table starts again. If it has, CX is reset and BX is increased by 4. The last lines keep BX from running outside the tables: CMP BX, offset datccw_fs · JBE next_step continues if BX is equal to or below the address of the last table; otherwise BX returns to the first table.

The behavior of the program shows in a long run. When port 7 always returns "ready", the first 128 bytes written to the port are the four bytes of datcw repeated 32 times. From the 129th byte on comes datccw (011, 001, 110, 010), from the 257th byte datcw_fs, and from the 385th byte datccw_fs; at the 513th byte datcw starts again.

Common mistake

Writing JB instead of JBE after CMP BX, offset datccw_fs. When BX points to the last table (010Eh), JB does not jump and BX returns to datcw at once; the CCW full-step table is never used. Equality is included so that the last table is counted too.

10.2.4.4Code trace: the first round

The trace assumes that port 7 returns 00h (busy) on the first read and 80h (ready) on all later reads. Table 10.2.14 shows the first four bytes and the end of the round; the repeated polling steps are abbreviated with "…".

Table 10.2.14: The first round of the stepper motor program (port 7 returns 00h first, then always 80h).
StepInstructionALBXSICXZFCFPort 7Explanation
1jmp start00h0000h0000h0000h00—jumps over the data tables
2mov bx, offset datcw00h0102h0000h0000h00—BX = 0102h: datcw (clockwise half step)
3mov si, 000h0102h0000h0000h00—SI = 0: position in the table
4mov cx, 000h0102h0000h0000h00—CX = 0: round counter
5wait: in al, 700h0102h0000h0000h00—AL = 00h: bit 7 = 0, motor busy
6test al, 10000000b00h0102h0000h0000h10—00h AND 80h = 0: ZF = 1
7jz wait00h0102h0000h0000h10—ZF = 1: read again
8wait: in al, 780h0102h0000h0000h10—AL = 80h: motor ready
9test al, 10000000b80h0102h0000h0000h00—80h AND 80h ≠ 0: ZF = 0
10jz wait80h0102h0000h0000h00—does not jump: a byte will be sent
11mov al, [bx][si]06h0102h0000h0000h00—AL ← [0102h + 0] = 06h = 110b
12out 7, al06h0102h0000h0000h0006hmagnets 2 and 1 on: half step (11.25°)
13inc si06h0102h0001h0000h0006hSI = 1
14cmp si, 406h0102h0001h0000h0106h1 − 4: CF = 1
15jb next_step06h0102h0001h0000h0106hJB jumps: next byte
…the ready bit is read (80h)
19mov al, [bx][si]04h0102h0001h0000h0006hAL ← [0103h] = 04h = 100b
20out 7, al04h0102h0001h0000h0004honly magnet 2 on
…SI = 2, polling
27mov al, [bx][si]03h0102h0002h0000h0004hAL ← [0104h] = 03h = 011b
28out 7, al03h0102h0002h0000h0003hmagnets 1 and 0 on
…SI = 3, polling
35mov al, [bx][si]02h0102h0003h0000h0003hAL ← [0105h] = 02h = 010b
36out 7, al02h0102h0003h0000h0002honly magnet 1 on: the first round is finished
37inc si02h0102h0004h0000h0002hSI = 4
38cmp si, 402h0102h0004h0000h1002h4 − 4 = 0: ZF = 1, CF = 0
39jb next_step02h0102h0004h0000h1002hJB does not jump
40mov si, 002h0102h0000h0000h1002hSI = 0: back to the start of the table
41inc cx02h0102h0000h0001h0002hCX = 1: one round (4 bytes) complete
42cmp cx, steps_before_direction_change02h0102h0000h0001h0102h1 − 20h: CF = 1
43jb next_step02h0102h0000h0001h0102hjumps: 32 rounds not yet complete, continue with the same table

The first part of the trace shows how polling works. With the 00h read at step 5 the TEST result is zero and ZF = 1, so JZ jumps back. With the 80h read at step 8, bit 7 is one; the TEST result is nonzero, ZF = 0, and the program moves on. TEST AL, 80h does not change AL; but the value of AL is wiped out anyway by the next MOV AL, [BX][SI]. The status byte is no longer needed.

The second part is the scan of the table. For SI = 0, 1, 2, 3 the values 06h, 04h, 03h, and 02h are written to port 7 in turn. When SI = 4, the result of CMP SI, 4 is zero: ZF = 1, CF = 0. JB jumps only when CF = 1, so it falls through. SI is reset and CX becomes one. After CMP CX, 20h CF = 1 (1 < 32) and the program begins a second round with the same table. In the first round the motor has turned four half steps, that is 45°.

10.2.4.5Real hardware: unipolar motor and ULN2003

The three-magnet motor of emu8086 is a model simplified for teaching. The type of stepper motor most often met in the laboratory is the unipolar motor. This motor has two center-tapped windings. Each winding is split in two at its center tap, giving four winding halves: A, B, A̅, and B̅. The center taps are connected to the motor's supply voltage (+V). That is why the motor has five or six wires.

To pass current through a winding half, its other end is pulled to ground. The winding current is hundreds of milliamperes, while one output pin of the 8255 can drive only a few milliamperes. A driver chip is placed in between: the ULN2003. The ULN2003 has seven Darlington transistor channels, and each channel can sink up to 500 mA. When the input of a channel is 1, its output pulls to ground and current flows through that winding half.

8255ULN2003PA01B1CAPA12B2CBPA23B3CA̅PA34B4CB̅COM+V (motor supply)unipolar motorAA̅BB̅center tap
Figure 10.2.11: Pins PA0–PA3 of the 8255 drive the winding halves A, B, A̅, and B̅ of a unipolar motor through four channels of the ULN2003. The center taps and the COM pin of the ULN2003 are connected to the motor supply (+V).

A winding is a coil, and the moment its current is cut a high voltage of opposite polarity appears across it. This voltage can destroy the transistor. Each channel of the ULN2003 has a diode for this purpose; when the COM pin is connected to +V, the diodes discharge the reverse voltage into the supply. Leaving the COM pin unconnected is the most common cause of a driver failing quickly.

A real motor is driven open loop: there is no "ready" bit as in the emu8086 motor. The program sets the speed of the motor by how long it waits between steps. If the wait is too short, the rotor cannot keep up with the next excitation and skips a step. The program cannot notice the lost step; the shaft is no longer at the position the program believes. For this reason the step interval is chosen according to the maximum step rate in the motor's datasheet.

Table 10.2.15: Excitation sequences of a unipolar motor (bits 3…0 of port A = B̅ A̅ B A).
DrivePort A sequenceProperty
Single phase (wave), full step01h 02h 04h 08hone winding half at a time; least current
Two phase, full step03h 06h 0Ch 09htwo winding halves at a time; higher torque
Half step01h 03h 02h 06h 04h 0Ch 08h 09hmixes the two sequences; the step angle is halved

The logic of the sequences is visible at bit level. In the single-phase sequence the 1 bit moves from A to B, A̅, and B̅: 0001, 0010, 0100, 1000. In the two-phase sequence two adjacent bits move together: 0011, 0110, 1100, 1001. The last byte, 1001b, says that B̅ and A are on together; the sequence closes into a ring. The half-step sequence interleaves the elements of these two: single, double, single, double. The step angle is thus halved; for example a 1.8° motor (200 steps per revolution) turns in 0.9° steps. If the sequence is applied in reverse, the motor turns in the opposite direction.

The tables of the emu8086 motor (110b, 100b …) cannot be applied to this four-phase motor. The bit layout of the three-magnet model differs from that of the motor with four winding halves. For a real motor the table is rewritten according to the order in which the windings are wired to the port.

10.2.4.6Code trace: half-step drive

The following program sends the half-step sequence to port A of the 8255. Port A is assumed to have been made an output earlier with 82h. The position in the sequence is held in the memory word pos.

org 100h
fwd:
inc  pos            ; reverse: dec pos
mov  bx, pos
and  bx, 7          ; index 0–7
mov  al, half[bx]
mov  dx, 310h       ; port A
out  dx, al
call delay          ; step gap = speed
jmp  fwd
delay: ret          ; (delay)
half db 01h,03h,02h,06h
     db 04h,0Ch,08h,09h
pos  dw 6

The key trick of the program is AND BX, 7. pos keeps increasing: 6, 7, 8, 9 … The sequence, however, has only eight elements. ANDing with 7 = 0000 0111b leaves only the last three bits of the number, so the result is always between 0 and 7. For 8 = 1000b the result is 0, for 9 it is 1, and the sequence wraps around by itself. This is a way to compute the remainder of division by 8 without a division instruction, and it works only for sequences whose length is a power of 2.

To turn backward it is enough to write DEC pos instead of INC pos. When pos drops by 1 from 0 it becomes FFFFh; AND BX, 7 turns this into 7 and the sequence is read from the end to the start. Because the counter lives in memory, INC pos is an instruction with a memory operand (FF 06 21 01): the processor reads the word, increments it, and writes it back. The delay routine in this trace is just RET; in a real program it sets the step interval, that is the speed of the motor.

Table 10.2.16: Trace of the program that drives the half-step sequence for a real motor (pos starts at 6).
StepInstructionposBXALSPPort AExplanation
1inc pos0007h0000h00hFFFEh—the word in memory 6 → 7
2mov bx, pos0007h0007h00hFFFEh—BX ← pos = 7
3and bx, 70007h0007h00hFFFEh—the index stays in the range 0–7: 7
4mov al, half[bx]0007h0007h09hFFFEh—AL ← half[7] = 09h = 1001b: B̅ and A
5mov dx, 310h0007h0007h09hFFFEh—DX = 310h: 8255 port A
6out dx, al0007h0007h09hFFFEh09hthe windings are driven: the field lies between A and B̅
7call delay0007h0007h09hFFFCh09hreturn address (0116h) onto the stack: SP = FFFCh
8delay: ret0007h0007h09hFFFEh09hthe delay routine is just RET here
9jmp fwd0007h0007h09hFFFEh09hnext step
10inc pos0008h0007h09hFFFEh09hpos = 8
11mov bx, pos0008h0008h09hFFFEh09hBX = 8
12and bx, 70008h0000h09hFFFEh09h8 AND 7 = 0: the sequence wraps around
13mov al, half[bx]0008h0000h01hFFFEh09hAL ← half[0] = 01h: only A
…DX = 310h
15out dx, al0008h0000h01hFFFEh01hthe field returns to winding A: one half step
…CALL, RET, JMP
19inc pos0009h0000h01hFFFEh01hpos = 9
20mov bx, pos0009h0009h01hFFFEh01hBX = 9
21and bx, 70009h0001h01hFFFEh01h9 AND 7 = 1
22mov al, half[bx]0009h0001h03hFFFEh01hAL ← half[1] = 03h: A and B
…DX = 310h
24out dx, al0009h0001h03hFFFEh03hthe field moves between A and B: one more half step

The angles in the trace show the direction of the field between the windings. 09h = 1001b says that B̅ and A are on together; the field points between the two, at about 315°. At 01h only A is on (0°), at 03h A and B (45°). Every OUT advances the field by a winding angle of 45°, that is the rotor by one half step.

BX0000hAL01hhalf[ ]0100310220630440C5086097port A (310h) = 01hABA̅B̅field ≈ 0°
Figure 10.2.12: When pos = 8, AND BX, 7 wraps the index to 0; with half[0] = 01h only winding A stays on and the field comes to 0°.

10.2.5LED display and 7-segment display

10.2.5.1The emu8086 LED display

The LED display of emu8086 is attached to port 199 and shows a five-digit decimal number. The 16-bit word written to the port is interpreted as a signed number in two's complement. The range that can be shown is therefore −32,768 … 32,767. Since 199 ≤ 255 the port is written as a constant: OUT 199, AX. AX is used because the display expects a word; OUT 199, AL would send only the low byte.

00355port 199 (2 bytes) · AX = 0163h
Figure 10.2.13: LED display: AX = 0163h written to port 199 appears as decimal 355.

The job of the display is to convert a binary number to decimal. The programmer thinks of the number in decimal, the assembler converts it to binary, and the device turns it back into decimal. MOV AX, 1234 writes 04D2h into AX (1234 = 4 · 256 + 210 = 04D2h). It is this binary word that goes to the display.

Negative numbers are written in two's complement. For −5678, first find the hexadecimal value of 5678: 162Eh. The two's complement is 10000h − 162Eh = E9D2h. When MOV AX, -5678 is written, the assembler does this computation and produces the code B8 D2 E9. The display sees that the highest bit of E9D2h is 1 and shows the number as −5678. Read as unsigned, the same word would be 59,858; the interpretation by the display determines the meaning of the bits.

The LED display example of emu8086 begins with the #make_bin# directive. This directive produces a plain binary file (.bin) that does not depend on DOS: no header, no PSP, only machine code. This is exactly the kind of file that would be written into the ROM of an embedded system.

10.2.5.2Code trace: the LED display program

#start=led_display.exe#
mov ax, 1234
out 199, ax
mov ax, -5678
out 199, ax
; write the port in an endless loop:
mov ax, 0
x1:
out 199, ax
inc ax
jmp x1
hlt              ; never runs

The program first shows two constant numbers, then sets up a counter that starts at 0 and increases without stopping. The loop contains INC AX and JMP x1 but no exit condition. The HLT after the loop is therefore never reached. HLT is written only to mark the end of the program.

Table 10.2.17: Trace of the LED display program; the display column is the signed value of the word last written to port 199.
StepInstructionAXDisplayExplanation
1mov ax, 123404D2h—1234 = 04D2h
2out 199, ax04D2h12341234 on the display
3mov ax, -5678E9D2h1234−5678 = 10000h − 162Eh = E9D2h
4out 199, axE9D2h−5678the display reads the word as signed: −5678
5mov ax, 00000h−5678counter 0
6out 199, ax0000h00 on the display
7inc ax0001h0AX = 1
8jmp x10001h0back to x1; HLT is never reached
9out 199, ax0001h11 on the display
10inc ax0002h1AX = 2
11jmp x10002h1loop
12out 199, ax0002h22 on the display

After the counter reaches 32,767 (7FFFh), INC AX makes it 8000h. The display reads 8000h as signed and shows −32,768. From there the counter rises to −1 (FFFFh) and then wraps to 0. INC sets OF to 1 at this crossing, but since the program does not look at the flags nothing happens.

In emu8086 with the step delay set to 0, the numbers stream by too fast to read. If a wait with INT 15h/86h is added to the loop, the counter can be followed by eye. For example, to wait 0.2 second after each number, add MOV CX, 3, MOV DX, 0D40h, MOV AH, 86h, INT 15h after the OUT. Because the wait changes AH, the counter must be kept in a register other than AX; for example count in BX and copy it to AX with MOV AX, BX before the OUT.

10.2.5.3The 7-segment display

The LED display of emu8086 decodes the number itself. In real hardware the program does this job. The most common numeric display is the seven-segment display. It has seven bar-shaped LEDs (a–g); the decimal point (dp) is the eighth LED. Each LED is called a segment (not to be confused with a memory segment).

abcdefgdpD70dpD61gD50fD40eD31dD21cD11bD01acommon cathode '3': 4Fhcommon anode '3': B0h (inverted)PA7 … PA0 → dp g f e d c b a
Figure 10.2.14: The 7-segment display and its connection to port A (PA7 … PA0 → dp g f e d c b a). For the digit '3', 4Fh is sent for a common cathode and its inverse B0h for a common anode.

One terminal of each of the display's eight LEDs is joined at a common pin. How this pin is wired distinguishes the two types. In a common-cathode (CC) display the common pin is at ground; giving 1 to a segment pin lights the LED. In a common-anode (CA) display the common pin is at +5 V; giving 0 to a segment pin lights the LED. The code for a common anode is therefore the bitwise inverse of the common-cathode code and is obtained with NOT AL. The LEDs are connected not directly to the port pins but each through a current-limiting resistor.

The segment code is computed from the segments that have to light. The bits of port A are in the order dp g f e d c b a: bit 0 = a, bit 6 = g, bit 7 = dp. For the digit '3', segments a, b, c, d, and g light; bits 0, 1, 2, 3, and 6 are one: 0100 1111b = 4Fh. For a common anode its inverse 1011 0000b = B0h is sent.

Table 10.2.18: Segment codes of the digits (in the order dp g f e d c b a).
DigitSegments litCommon cathode (CC)Common anode (CA)
0a b c d e f3FhC0h
1b c06hF9h
2a b d e g5BhA4h
3a b c d g4FhB0h
4b c f g66h99h
5a c d f g6Dh92h
6a c d e f g7Dh82h
7a b c07hF8h
8a b c d e f g7Fh80h
9a b c d f g6Fh90h

The table is not limited to digits. Hexadecimal digits and some letters can also be written with seven segments. For 'A', a b c e f g light: 0111 0111b = 77h. For a lowercase 'b', c d e f g: 0111 1100b = 7Ch. The minus sign is segment g alone: 0100 0000b = 40h.

10.2.5.4Code table and XLAT

Converting a digit to a segment code is a table lookup. The 8086 has a one-byte instruction for this: XLAT (translate). XLAT performs AL ← DS:[BX + AL]. BX points to the start of the table and AL holds the index; the byte in the table is written into AL.

; digit (0–9) to segment code
mov  bx, offset segtab
mov  al, 3          ; digit
xlat                ; AL = [BX + AL] = 4Fh
; not al            ; if common anode
mov  dx, 310h       ; 8255 port A
out  dx, al
ret
segtab db 3Fh,06h,5Bh,4Fh,66h
       db 6Dh,7Dh,07h,7Fh,6Fh

In the example AL = 3, and XLAT fetches byte number 3 (counting from 0) of the code table, 4Fh. If the display is common-anode, the NOT AL in the comment line is enabled and AL becomes B0h. The result is written to port A of the 8255. The only restriction of XLAT is that the table has at most 256 bytes; AL is an 8-bit index. The instruction does not touch the flags and takes 11 clock cycles.

The advantage of the table method over computation is clear. There is no short way to derive the segment code from the digit with a formula; ten separate comparisons would be needed. The table gives the result for every digit in the same time with a single instruction. If the display changes (for example if the segment pins are wired to the port in a different order), only the table is rewritten.

Common mistake

Giving the digit to the table as ASCII. The code of the character '3' read from the keyboard is 33h = 51; XLAT reads 51 bytes past the start of the table and fetches a random byte from outside the table. An ASCII digit is first converted to a number with SUB AL, 30h.

10.2.5.5Multiplexed scanning

Connecting a separate 8-bit port to each digit of a four-digit display would need 32 pins. Multiplexing reduces this number to 12. The segment pins of the same name on the four digits are tied together and go to the shared port A. The common pin of each digit is connected through its own transistor to one bit of port C. At any moment the program lights only one digit: it writes the code of that digit to port A and sets only that digit's bit to 1 in port C.

When the digits are lit one after another quickly, the eye sees all four lit together. If about 4 ms is given to each digit, a full pass takes 16 ms, so the scan rate is 1 / 16 ms ≈ 62 Hz. The human eye does not notice flicker above about 50 Hz. If the scan slows down (for example 20 ms per digit), a clear flicker is seen on the display.

scan:
mov  si, 0
next_dig:
mov  dx, 312h       ; port C: digit select
mov  al, 0
out  dx, al         ; blank all digits first
mov  al, digits[si]
mov  bx, offset segtab   ; table above
xlat
mov  dx, 310h       ; port A: segments
out  dx, al
mov  al, select[si] ; 01h, 02h, 04h, 08h
mov  dx, 312h
out  dx, al         ; only this digit lit
call delay_4ms
inc  si
cmp  si, 4
jb   next_dig
jmp  scan
delay_4ms:          ; ≈ 4 ms delay
mov  cx, 1000
loop $
ret
digits db 1, 2, 3, 4
select db 01h, 02h, 04h, 08h

The most important line of the loop is the OUT DX, AL that blanks all digits before the digit is changed (AL = 0, DX = 312h). Without this line, at the moment the new code is written to port A the previous digit would still be lit. The new code would appear for an instant on the previous digit too and leave a faint trace there; this is called ghosting. The correct order is: blank everything, write the segment code, light only the wanted digit, wait.

The select table holds the byte to be written to port C for each digit. 01h, 02h, 04h, and 08h set PC0, PC1, PC2, and PC3 to 1 respectively. These values could also have been produced by shifting 1 left by SI (MOV CX, SI · MOV AL, 1 · SHL AL, CL); the table is both shorter and faster.

The following abbreviated program scans the number 2026 once across the display. The delay routine is removed, and a single pass and RET replace the endless loop.

org 100h
mov  bx, offset segtab
mov  si, 0
next_dig:
mov  dx, 312h      ; port C (digit)
mov  al, 0
out  dx, al        ; all blank
mov  al, digits[si]
xlat               ; segment code
mov  dx, 310h      ; port A (segments)
out  dx, al
mov  al, select[si]
mov  dx, 312h
out  dx, al        ; one digit lit
inc  si
cmp  si, 4
jb   next_dig
ret
segtab db 3Fh,06h,5Bh,4Fh,66h
       db 6Dh,7Dh,07h,7Fh,6Fh
digits db 2, 0, 2, 6
select db 01h, 02h, 04h, 08h

BX is loaded once outside the loop, because it does not change in the loop. The code is 36 bytes and the tables follow right behind it: segtab is at 0124h, digits at 012Eh, and select at 0132h. Table 10.2.19 gives the important rows of the trace; the port columns show the last value written to the port up to that moment.

Table 10.2.19: Trace of the program that scans 2026 on a four-digit display by multiplexing (common-cathode codes).
StepInstructionSIALPort APort CExplanation
1mov bx, offset segtab0000h00h——BX = 0124h: the start of the code table
2mov si, 00000h00h——SI = 0: first position
3mov dx, 312h0000h00h——DX = 312h: port C, digit select
4mov al, 00000h00h——AL = 0
5out dx, al0000h00h—00hall digits blank: no ghosting
6mov al, digits[si]0000h02h—00hAL ← digits[0] = 2
7xlat0000h5Bh—00hAL ← [BX + 2] = 5Bh
8mov dx, 310h0000h5Bh—00hDX = 310h: port A, segments
9out dx, al0000h5Bh5Bh00hthe segment code goes out on the port
10mov al, select[si]0000h01h5Bh00hAL ← select[0] = 01h
11mov dx, 312h0000h01h5Bh00hDX = 312h
12out dx, al0000h01h5Bh01honly position 1 lit: "2"
13inc si0001h01h5Bh01hSI = 1
…CMP, JB; position 2: port C ← 00h, digit 0
20xlat0001h3Fh5Bh00hXLAT: AL = 3Fh
22out dx, al0001h3Fh3Fh00hport A ← 3Fh
25out dx, al0001h02h3Fh02honly position 2 lit: "0"
…position 3: digit 2
33xlat0002h5Bh3Fh00hXLAT: AL = 5Bh
38out dx, al0002h04h5Bh04honly position 3 lit: "2"
…position 4: digit 6
46xlat0003h7Dh5Bh00hXLAT: AL = 7Dh
51out dx, al0003h08h7Dh08honly position 4 lit: "6"
52inc si0004h08h7Dh08hSI = 4
53cmp si, 40004h08h7Dh08hequal: CF = 0
54jb next_dig0004h08h7Dh08hthe loop ends
55ret0004h08h7Dh08hin a real program the scan starts over

In the trace the value of port A changes while port C is 00h. For example, at step 20, when XLAT brings 3Fh, port A is still 5Bh, but because port C = 00h no digit is lit. After port A becomes 3Fh (step 22), port C is made 02h (step 25). Each digit lights while its own segment code is on the port and only it is selected.

10.2.6Thermometer and thermostat

10.2.6.1The device

The thermometer device of emu8086 represents the temperature of a room and the heater in it. It uses two ports. IN AL, 125 reads the current air temperature in degrees Celsius; the value is a signed byte, so it can be between −128 and 127 °C. OUT 127, AL controls the heater: AL = 1 turns the heater on, AL = 0 turns it off. While the heater is on the temperature rises slowly, and while it is off it falls.

-4004080120port 125: 70 °Cheater OFFport 127 = 0target range: 60–80 °C
Figure 10.2.15: The thermometer device: the temperature read from port 125 is 70 °C and the heater is off (port 127 = 0). The target range is 60–80 °C.

The goal is a thermostat that keeps the temperature in the range 60–80 °C. The rule is simple: if the temperature drops below 60 the heater is switched on, if it rises above 80 it is switched off, and in between the heater is left alone. This "hands-off" zone is left deliberately. If a single threshold (say 70 °C) were used, the heater would switch on and off several times a second while the temperature oscillated around the threshold. The gap between the two thresholds is called hysteresis; household thermostats, refrigerators, and air conditioners work the same way.

10.2.6.2The thermostat program

; make DS equal to CS:
mov ax, cs
mov ds, ax
start:
in  al, 125
cmp al, 60
jl  low
cmp al, 80
jle ok
jg  high
low:
mov al, 1
out 127, al      ; heater on
jmp ok
high:
mov al, 0
out 127, al      ; heater off
ok:
jmp start        ; endless loop

The first two lines set DS equal to CS. Because a constant cannot be written directly into a segment register, the value goes into AX first. There are no variables in this program, so the lines are not strictly needed; they are left over from the original emu8086 sample. In a .COM program DS already equals CS.

The loop begins with IN AL, 125. Two comparisons follow. CMP AL, 60 performs AL − 60 and only sets the flags. JL low jumps if the result is "less", that is if SF ≠ OF. If it does not jump, the temperature is at least 60. CMP AL, 80 and JLE ok test the second threshold: if ZF = 1 or SF ≠ OF the temperature is at most 80 and the program returns to the loop without touching the heater. If neither jumps, the temperature is above 80; JG high goes to the code that switches the heater off.

The condition of the JG high line is in fact always true. If JLE did not jump, the temperature must be above 80; JG therefore always jumps, and JMP high could have been written instead. The line cannot be deleted altogether: the low block sits right below it and the program would turn the heater on in a hot room. JG is preferred because it states the condition openly to the reader.

All the comparisons are made with signed jumps (JL, JLE, JG), because the temperature can be negative. Unsigned jumps (JB, JBE, JA) count the byte as a number between 0 and 255. This difference reverses the behavior of the program at negative temperatures.

Theorem 10.2.1 (Signed comparison)

If a and b are compared as signed numbers after CMP a, b, then a < b holds if and only if SF ≠ OF. a ≤ b holds when ZF = 1 or SF ≠ OF. In an unsigned comparison, a < b holds if and only if CF = 1.

10.2.6.3Code trace

The trace assumes that port 125 returns 55, 70, and 85 °C in turn and that the heater is off at the start. The three values test the three paths of the program once each: cold, in range, and hot.

Table 10.2.20: Trace of the thermostat program; port 125 returns 55, 70, and 85 °C in turn, and the heater is off at the start.
StepInstructionALZFSFOFCFHeaterExplanation
1mov ax, cs00h0000offAX = CS = 0700h
2mov ds, ax00h0000offDS = 0700h; a constant cannot be written directly into a segment register
3in al, 12537h0000off55 °C = 37h
4cmp al, 6037h0101off55 − 60 = −5: SF = 1, OF = 0
5jl low37h0101offSF ≠ OF: jumps (low)
6mov al, 101h0101offAL = 1
7out 127, al01h0101onthe heater is switched on
8jmp ok01h0101onjump to ok
9jmp start01h0101onnew measurement
10in al, 12546h0101on70 °C = 46h
11cmp al, 6046h0000on70 − 60 = 10: SF = 0, OF = 0
12jl low46h0000onSF = OF: does not jump
13cmp al, 8046h0101on70 − 80 = −10: SF = 1, ZF = 0
14jle ok46h0101onZF = 1 or SF ≠ OF: jumps; the heater is left alone
15jmp start46h0101onnew measurement
16in al, 12555h0101on85 °C = 55h
17cmp al, 6055h0000on85 − 60 = 25
18jl low55h0000ondoes not jump
19cmp al, 8055h0000on85 − 80 = 5: SF = 0, ZF = 0
20jle ok55h0000ondoes not jump
21jg high55h0000onZF = 0 and SF = OF: jumps (high)
22mov al, 000h0000onAL = 0
23out 127, al00h0000offthe heater is switched off
24jmp start00h0000offnew measurement

In the first measurement 55 − 60 = −5. Since the result is negative, SF = 1; there is no signed overflow, so OF = 0. Because SF ≠ OF, JL jumps and the heater is switched on. CF is also 1, because 55 < 60 unsigned as well; for these values the signed and unsigned interpretations give the same result.

In the second measurement 70 − 60 = 10 gives SF = OF = 0 and JL does not jump. 70 − 80 = −10 sets SF = 1; JLE jumps and the program returns without touching the heater. Because the heater was switched on in the previous round, it stays on; the temperature keeps rising. In the third measurement 85 passes both comparisons: JG jumps on the condition ZF = 0 and SF = OF, and the heater is switched off.

The interactive thermostat in the slides runs the same program over time: the temperature rises and falls according to the state of the heater, and the lines the program is executing are highlighted. You can see the temperature moving back and forth between 60 and 80 while the heater changes state only at the thresholds.

10.2.6.4Negative temperatures and unsigned jumps

Let the temperature be −10 °C. Port 125 returns the two's complement of −10, F6h. For the signed program, CMP AL, 60 computes −10 − 60 = −70. Since the result is greater than −128 there is no overflow: SF = 1, OF = 0. JL jumps and the heater is switched on. This is the correct behavior.

If the program had been written with unsigned jumps (JB low, JBE ok, JA high), F6h would count as 246. 246 < 60 is false: CF = 0 and JB does not jump. 246 ≤ 80 is false too; JA jumps and the heater is switched off. While the room freezes the thermostat keeps the heater off. The same error appears at every temperature between −1 and −128, because all of them are greater than 127 when read as unsigned.

Common mistake

Choosing a jump instruction without checking whether the value read from the device is signed or unsigned. The rule comes from the meaning of the data: quantities that can be negative, such as temperature, acceleration, or a speed difference, are compared with the JL/JG family; quantities that are never negative, such as addresses, counters, ASCII codes, and status bytes, are compared with the JB/JA family.

10.2.7Printer

10.2.7.1The DOS printer service and control characters

The printer of emu8086 is attached to port 130, but the program does not write to the port directly. Instead it uses the DOS printer service: INT 21h, AH = 05h sends the character in DL to the printer (the PRN device). The service also does the job of waiting for the printer to be ready. On a real PC this service uses the BIOS INT 17h routine, which in turn uses the registers of the parallel port. The program does not have to know any of these details.

Most of the bytes sent to the printer are characters to be printed. Some are control characters: they print nothing on the paper but move the print head or the paper (Table 10.2.21).

Table 10.2.21: Control characters that command the printer.
KodAdEffect
0Ah (10)LF (line feed)one line down
0Dh (13)CR (carriage return)return to the start of the line
09h (9)HT (horizontal tab)to the next horizontal tab stop (every 8 columns)
0Ch (12)FF (form feed)eject the page, move to a new page

The names of these characters come from the typewriter. CR returns the typewriter's carriage (the sled that carries the paper) to the start of the line; LF pushes the paper up by one line. On a typewriter the two motions were made with separate levers, and the printer likewise expects them as separate characters. To move to a new line both are needed. The usual order is CR + LF, but LF + CR gives the same result: the head first goes down, then to the start. If only CR is sent, the head returns to the start of the same line and the following characters are printed over the old ones. Vertical tab (VT) is 0Bh and is not used in this program.

Hello, Printer!********Have a nice…0Ah, 0Dh: start of the next lineCR (13): back to the start of the same lineHT (9): jump to column 8 → print overFF (12): eject the page, new page
Figure 10.2.16: Control characters on the printer paper: LF and CR take the head to the start of the next line; CR alone returns to the start of the same line; HT jumps to column 8; FF ejects the page.

10.2.7.2Data section and length computation

org 100h
jmp start
msg  db "Hello, Printer!", 0Ah, 0Dh
     db "***************"
     db 13, 9           ; CR and horizontal tab (HT)
     db "Have a nice printing day!"
msg_end db 0
msg2 db "press any key to eject the page.$"

The text is split over several DB lines, but in memory it is a single unbroken sequence of bytes. The number of characters to print is not counted by hand; the assembler is made to compute it:

offset msg_end − offset msg = 15 + 2 + 15 + 2 + 25 = 59 = 3Bh bytes.

"Hello, Printer!" is 15 characters, LF with CR 2, the asterisks 15, CR with HT 2, and "Have a nice printing day!" 25. Since msg starts at 0102h, msg_end is at 0102h + 3Bh = 013Dh. The 0 byte at msg_end is not printed; the label is there only to mark the address right after the last character. If the text changes, the length is computed correctly by itself.

msg2 ends with '$'. This string goes not to the printer but to the screen and is printed with INT 21h/09h; service 09h writes up to the '$' character. The 33-byte msg2 starts at 013Eh and ends at 015Eh; the code therefore starts at 015Fh, and the JMP start (EB 5D) in the first line jumps there.

10.2.7.3The print loop

start:
mov dl, 12        ; form feed: new page
mov ah, 5
int 21h
mov si, offset msg
mov cx, offset msg_end - offset msg
print:
mov dl, [si]
mov ah, 5         ; DOS printer function
int 21h
inc si            ; next character
loop print
mov dx, offset msg2
mov ah, 9
int 21h           ; message on screen
mov ax, 0
int 16h           ; wait for a key
mov dl, 12        ; eject the page
mov ah, 5
int 21h
ret

To start with a clean page the program first sends a form feed. Then SI takes the start of the string and CX the number of characters. The loop body reads one character into DL, writes 05h into AH, and calls the service. MOV AH, 5 is repeated in every round; because INT 21h services may change AH, this is the safe way. INC SI moves on to the next character; LOOP print decrements CX and goes back to the top if it is not zero. The loop runs exactly 59 times.

After the loop "press any key to eject the page." is written to the screen and a key is awaited with INT 16h/00h. When the user presses a key, a final form feed ejects the page from the printer. The program ends with RET.

Table 10.2.22: Trace of the printer program (selected steps; the "To printer" column is the character sent to the printer at that step).
StepInstructionCXDLSITo printerExplanation
1jmp start0000h00h0000hjumps over the data bytes to 015Fh
2mov dl, 120000h0Ch0000hDL = 12 = 0Ch: form feed
3mov ah, 50000h0Ch0000hAH = 05h: DOS printer output
4int 21h0000h0Ch0000hFFthe printer moves to a new page
5mov si, offset msg0000h0Ch0102hSI = 0102h: msg
6mov cx, offset msg_end - offset msg003Bh0Ch0102h013Dh − 0102h = 3Bh = 59 characters
7mov dl, [si]003Bh48h0102hDL ← [0102h] = 'H'
8mov ah, 5003Bh48h0102hAH = 05h
9int 21h003Bh48h0102h'H''H' goes to the printer
10inc si003Bh48h0103hSI = 0103h
11loop print003Ah48h0103hCX = 58 ≠ 0: back to print
…continues character by character
84int 21h002Ch0Ah0111hLFbyte 16: LF, the paper advances one line
89int 21h002Bh0Dh0112hCRbyte 17: CR, start of line
…15 asterisks
169int 21h001Bh0Dh0122hCRbyte 33: CR; no LF, so the head returns to the start of the same line
174int 21h001Ah09h0123hHTbyte 34: HT, jumps to the eight-column tab stop
…"Have a nice printing day" is printed over the asterisks
297mov dl, [si]0001h21h013ChDL ← [013Ch] = '!'
299int 21h0001h21h013Ch'!'last character
300inc si0001h21h013DhSI = 013Dh = msg_end
301loop print0000h21h013DhCX = 0: the loop ends
302mov dx, offset msg20000h3Eh013DhDX = address of msg2 (013Eh)
304int 21h0000h3Eh013Dhmessage on screen (up to the $)
306int 16h0000h3Eh013Dhwaits for a key
309int 21h0000h0Ch013DhFFlast form feed: the paper is ejected
310ret0000h0Ch013Dhthe program ends

The "To printer" column of the trace shows the byte sent to the printer at each INT 21h. The LF at step 84 and the CR at step 89 bring the paper to the start of the second line. After the CR at step 169 there is no LF: the head returns to the start of the same line, at the asterisks. The HT at step 174 moves the head to column 8 (counting from 0). "Have a nice printing day!" therefore starts after the first eight asterisks and is printed over the remaining seven.

10.2.7.4What appears on paper?

When the program ends, the page has two lines:

Hello, Printer!
********Have a nice printing day!

On the second line the first eight asterisks are visible; asterisks 9 to 15 are printed on the same place as the letters of the words "Have a ". On a real dot-matrix printer two characters would appear on top of each other at these places; the paper view of emu8086 shows the upper character. This combination of carriage return and tab characters was used deliberately in the typewriter era to get underlined or bold text: the same line was printed twice.

Common mistake

Writing the character count by hand: MOV CX, 59. When a single letter is added to the text, the number becomes wrong; either the last character is not printed or the bytes beyond msg_end (here the start of msg2) go to the printer. The difference offset msg_end - offset msg is computed at assembly time and is updated automatically with the text.

10.2.8Robot

10.2.8.1Ports, commands, and status bits

The robot of emu8086 moves in a grid world. The world has walls and lamps. The robot can examine the cell in front of it, go forward, turn left or right, and switch the lamp in front of it on and off. The world is edited with the toolbox in the device window: walls and lamps are added and the robot's position is changed.

command (9): 00000001data (10): 00000000status (11): 00000000lit lampunlit lampwall
Figure 10.2.17: The robot world: walls (hatched), lit and unlit lamps, the robot, and the current bytes of the three ports.

The robot uses three ports, and this trio is a pattern often seen in real devices as well. Port 9 is the command port: the program writes what the robot should do here (OUT). Port 10 is the data port: the result of the examine command is read from here (IN). Port 11 is the status port: whether the robot is busy, whether new data is available, and whether the last command gave an error are read from here (IN).

Table 10.2.23: Robot commands (port 9) and examine results (port 10).
CommandEffectDataAhead
0do nothing255 (FFh)wall
1move forward0empty
2turn left7lit lamp
3turn right8unlit lamp
4examine what is ahead
5turn the lamp on
6turn the lamp off
Table 10.2.24: The robot status byte (port 11).
BitIf 1
bit 0new data in the data register
bit 1robot busy (command in progress)
bit 2error in the last command

Each bit of the status byte carries a separate piece of information, and several can be 1 at the same time. 03h = 0000 0011b says that the robot is busy and also that there is unread data in the data register. 05h = 0000 0101b shows that the new-data and error bits are set together. The program therefore does not compare the status with a number (CMP AL, 2); it tests only the bit it cares about (TEST AL, 010b).

10.2.8.2Find the lamp and light it

The following program makes the robot wander through the world and light the unlit lamps it meets. On every round it examines what is ahead. If there is a wall it turns right, if there is an unlit lamp it lights it, and otherwise it goes forward.

#start=robot.exe#
main_loop: CALL wait_ready
        MOV  AL, 4         ; examine
        OUT  9, AL
        CALL wait_data
        IN   AL, 10
        CMP  AL, 0FFh      ; wall?
        JE   turn
        CMP  AL, 8         ; lamp off?
        JNE  advance
        CALL wait_ready
        MOV  AL, 5         ; lamp on
        OUT  9, AL
        JMP  main_loop
turn:   MOV  AL, 3         ; turn right
        JMP  send
advance: MOV AL, 1         ; forward
send:   PUSH AX            ; keep command
        CALL wait_ready
        POP  AX
        OUT  9, AL
        JMP  main_loop

wait_ready PROC
b1:     IN   AL, 11
        TEST AL, 010b      ; busy?
        JNZ  b1
        RET
wait_ready ENDP

wait_data PROC
v1:     IN   AL, 11
        TEST AL, 001b      ; new data?
        JZ   v1
        RET
wait_data ENDP

The program rests on two wait routines. wait_ready tests bit 1 of the status byte: as long as the busy bit is 1 (ZF = 0), JNZ jumps back. When the robot finishes the previous command, the routine returns. wait_data tests bit 0 and returns on the opposite condition: it waits with JZ as long as the new-data bit is 0 (ZF = 1). The two routines have the same structure; only the mask and the jump condition differ.

Before every command the program waits for the busy bit to clear. After the examine (4) command it waits for the data-ready bit; only then is port 10 read. If the value read is FFh, JE turn goes to the turn-right code. If it is 8, JNE does not jump and the lamp is lit. For any other value JNE advance goes to the go-forward code. The "turn right" and "go forward" paths join at the send label: the command in AL is written to the port and the loop starts over.

The waiting jobs are routines called with CALL. On each call the return address is pushed on the stack (SP decreases by 2) and RET takes it back. Instead of writing the same wait loop three times in the program, a single routine called from three places makes the code shorter and reduces the chance of errors.

10.2.8.3Preserving AL

There is a subtlety on the send path. AL carries the robot's command (1 or 3). But before the command is sent wait_ready is called, and that routine overwrites AL with the status byte through IN AL, 11. When the routine returns, AL is no longer the command but the last status read. For this reason the command is saved on the stack with PUSH AX before the call and restored with POP AX after it. Because PUSH does not accept an 8-bit register, AX is pushed instead of AL.

Table 10.2.25 traces one round with a wall in front of the robot. It is assumed that port 11 returns 00h (ready), 01h (data available), 03h (busy and data available), and 01h in turn, and that port 10 returns FFh (wall).

Table 10.2.25: Trace of the program with a wall in front of the robot; port 11 returns 00h, 01h, 03h, 01h in turn, and port 10 returns FFh.
StepInstructionALSPZFPort 9Explanation
1main_loop: CALL wait_ready00hFFFCh0—return address 0103h onto the stack
2b1: IN AL, 1100hFFFCh0—status = 00h
3TEST AL, 010b00hFFFCh1—bit 1 = 0: not busy, ZF = 1
4JNZ b100hFFFCh1—does not jump
5RET00hFFFEh1—return: SP = FFFEh
6MOV AL, 404hFFFEh1—command 4: examine
7OUT 9, AL04hFFFEh104hthe robot examines what is ahead
8CALL wait_data04hFFFCh104hwaits for data
9v1: IN AL, 1101hFFFCh104hstatus = 01h: new data available
10TEST AL, 001b01hFFFCh004hbit 0 = 1: ZF = 0
11JZ v101hFFFCh004hdoes not jump
12RET01hFFFEh004hreturn
13IN AL, 10FFhFFFEh004hdata = FFh: wall
14CMP AL, 0FFhFFhFFFEh104hequal: ZF = 1
15JE turnFFhFFFEh104hjumps to turn
16turn: MOV AL, 303hFFFEh104hcommand 3: turn right
17JMP send03hFFFEh104hsend
18send: PUSH AX03hFFFCh104hAX = 0003h onto the stack: SP = FFFCh
19CALL wait_ready03hFFFAh104hreturn address onto the stack: SP = FFFAh
20b1: IN AL, 1103hFFFAh104hstatus = 03h: AL overwritten
21TEST AL, 010b03hFFFAh004hbit 1 = 1: busy, ZF = 0
22JNZ b103hFFFAh004hread again
23b1: IN AL, 1101hFFFAh004hstatus = 01h
24TEST AL, 010b01hFFFAh104hbit 1 = 0: ZF = 1
25JNZ b101hFFFAh104hdoes not jump
26RET01hFFFCh104hreturn: SP = FFFCh, AL = 01h
27POP AX03hFFFEh104hAL = 03h is back
28OUT 9, AL03hFFFEh103h"turn right" goes to the robot
29JMP main_loop03hFFFEh103hthe loop starts over

At step 18 AX = 0003h is pushed and SP drops to FFFCh. The CALL at step 19 also pushes the return address: SP = FFFAh. Inside the routine AL becomes 03h (busy) and then 01h. The RET at step 26 takes the return address; AL holds 01h. The POP AX at step 27 brings back 03h, and at step 28 the right value, 3, goes to the port. The stack is balanced too: SP returns to where it started, FFFEh.

Had PUSH AX and POP AX been deleted, 01h would go to the port in the same scenario: "go forward". The robot would try to walk into the wall and the error bit (bit 2) would be set. Since the program does not check this error, on the next round it examines again, sees the wall again, and repeats the same error: the robot gets stuck in front of the wall.

Common mistake

Relying, after a routine call, on the old value of a register the routine uses. wait_ready changes AL, and there is no way to tell this from the routine's name. Either the routine saves the registers it changes itself (PUSH on entry, POP on exit), or the caller puts the value it wants to protect on the stack. The robot program uses the second way.

The program has two more shortcomings. First, the error bit is never read. A "forward" command into a wall sets bit 2; a robust program should read the status byte after every command and test this bit. Second, there is the cost of polling: the processor is completely busy while waiting for each movement of the robot. In a real robot controller this waiting is done with interrupts, and in between the processor handles sensor data.

10.2.9The simple I/O test device

10.2.9.1Ports 110 and 112

The test device (simple io test) is a window made for trying out the IN and OUT instructions. Port 110 holds a byte and port 112 holds a word. The values typed into the window become input to the program; for a hexadecimal value an h is appended (for example A7h). The values the program writes to the ports also appear in the window. The input ports are refreshed every 100 ms. A new value typed into the window is therefore read within 100 ms at the latest, even while the program is running.

simple io testwrite byte to port 110:write word to port 112:read byte from port 110:A8hread word from port 112:1235h
Figure 10.2.18: The test device window. The program has written A8h to port 110 and 1235h to port 112; the window shows these values.

The window is very valuable as a debugging tool. While writing a device program you can see here whether the value going to the port is correct; input values can also be supplied by hand without a device. In the example in the slides, A7h is entered in the window for port 110 and 1234h for port 112. The program adds 1 to the first and writes A8h back, and adds 1 to the second and writes 1235h back.

10.2.9.2Code trace: byte and word I/O

org 100h
in  al, 110      ; read byte
inc al
out 110, al      ; write byte
in  ax, 112      ; read word
add ax, 1
out 112, ax      ; write word
ret

When the same program is run with boundary values, the behavior of the flags comes out. Let FFh be entered in the window for port 110 and 7FFFh for port 112.

Table 10.2.26: Trace of the test device program; port 110 = FFh and port 112 = 7FFFh are entered in the window.
StepInstructionAXZFSFOFCFI/OExplanation
1in al, 11000FFh0000110 → FFhbyte read: AL = FFh
2inc al0000h1000FFh + 1 = 00h: ZF = 1; INC does not touch CF
3out 110, al0000h1000110 ← 00hport 110 = 00h in the window
4in ax, 1127FFFh1000112 → 7FFFhword read: AL ← port 112, AH ← port 113
5add ax, 18000h01107FFFh + 1 = 8000h: the sum of two positives is negative, OF = 1
6out 112, ax8000h0110112 ← 8000hport 112 = 8000h in the window
7ret8000h01100000h popped from the stack → IP
8INT 20h (PSP:0000)8000h0110the program ends

The first part is an 8-bit overflow. The 9th bit of the result FFh + 1 = 100h does not fit in AL, and AL = 00h. ZF = 1. The INC instruction does not change CF; CF stays at its previous value, 0. Had the same operation been done with ADD AL, 1, CF would be 1. 00h is written to the port.

The second part is a signed overflow. IN AX, 112 takes AL from port 112 and AH from port 113: AX = 7FFFh, +32,767 as signed. The result of ADD AX, 1 is 8000h. The sum of two positive numbers appears as a negative number: OF = 1, SF = 1. There is no overflow in the unsigned sum (32,767 + 1 = 32,768 < 65,536), so CF = 0. The window shows port 112 = 8000h. Had the same word been written to the LED display, it would show −32,768.

10.2.10The common pattern

The seven devices look very different from one another: one lights lamps, one turns a motor, one reads a temperature. Their programs, however, are variations of the same skeleton (Table 10.2.27).

Table 10.2.27: Devices, their ports, and their basic ideas.
DevicePortBasic idea
Traffic lights4Each bit is a lamp; state table and INT 15h/86h wait.
Stepper motor7Bits 0–2 magnets, bit 7 ready; half step 11.25°, full step 22.5°.
LED display199Word, signed decimal display.
Thermometer125, 127Read, signed comparison, heater on/off.
Printer130INT 21h/05h; control characters LF, CR, HT, FF.
Robot9, 10, 11Command, data, status; poll the busy and data bits.
Test device110, 112Byte and word I/O experiment.
8255 PPI (real)310h–313hThe control word (for example 82h) sets the port directions; port > 255 → DX.

The common pattern has four steps: read the status, test the relevant bit, write or read the data if ready, go back to the loop. In the traffic lights the "status" is time, and waiting replaces testing. In the thermostat the status is the temperature read itself. In the stepper motor and the robot the status is bits in a separate port. In every case IN and OUT work only with AL/AX, and DX is used if the port is above 255. Most devices are driven in an endless loop.

10.2.11Exercises and solutions

Exercise 1. What is the port 4 value that lights only the yellow lamps in all directions?

The yellow lamps are at bits 3k + 1: bits 1, 4, 7, and 10. The word is 2 + 16 + 128 + 1024 = 1170 = 0000 0100 1001 0010b = 0492h.

Exercise 2. What must CX and DX be for a 2.5-second wait with INT 15h/86h?

2.5 s = 2,500,000 µs = 002625A0h. The high word is CX = 0026h and the low word DX = 25A0h. In the source code write mov cx, 26h and mov dx, 25A0h.

Exercise 3. What hexadecimal value is written to AX to show −1 on the LED display?

The 16-bit two's complement of −1 is 10000h − 1 = FFFFh. When mov ax, -1 is written, the assembler produces the same value.

Exercise 4. How is the thermostat adapted to the range 20–25 °C? What would happen at −10 °C if JB were used instead of JL?

Only two constants change: cmp al, 20 · jl low · cmp al, 25 · jle ok · jg high. −10 °C arrives from the port as F6h. In a signed comparison −10 < 20 and the heater is switched on. JB, however, counts F6h as 246; 246 < 20 is false, so it does not jump and the heater is not switched on. If the unsigned JA is used as well, the heater is switched off.

Exercise 5. Which lines of the stepper motor program must change to turn the motor only clockwise and in full steps?

BX must point to the full-step table at the start: mov bx, offset datcw_fs. The part that changes the table (from inc cx to the last jmp next_step) is deleted, and right after mov si, 0 comes a plain jmp next_step. Since CX is no longer used, the line mov cx, 0 is unnecessary too.

Exercise 6. How is the shortest program that prints "Hello" on the printer and ejects the page written?

One could write MOV DL, 'H' · MOV AH, 5 · INT 21h for every character; with a string and a loop it is shorter:

org 100h
mov  si, offset msg
mov  cx, 6           ; "Hello" + FF
again: mov dl, [si]
mov  ah, 5
int  21h
inc  si
loop again
ret
msg  db "Hello", 12

The 12 (FF) added to the end of the string ejects the page, so there is no need for a separate form feed call.

Exercise 7. On an 8 MHz 8086, what is N for a delay of about 1 ms with mov cx, N / loop?

1 ms is 8,000 clock cycles. The equation 17N − 8 = 8,000 gives N ≈ 471.06. With N = 471, 17 · 471 − 8 = 7,999 cycles, that is 0.999875 ms.

Exercise 8. What is the control word of the 8255 for A input, B output, and all of C input (mode 0)?

D7 = 1, D6 D5 = 00, D4 = 1 (A input), D3 = 1 (C upper input), D2 = 0, D1 = 0 (B output), D0 = 1 (C lower input): 1 00 1 1 0 0 1b = 99h.

Exercise 9. What are the codes of the digit '5' and the letter 'H' on a common-anode display (in the order dp g f e d c b a)?

For '5' the common-cathode code is 6Dh = 0110 1101b; its inverse is 1001 0010b = 92h. For 'H', b, c, e, f, and g light: 0111 0110b = 76h; the common-anode code is 1000 1001b = 89h.

10.2.12Summary

  • A peripheral shows itself to the processor through its registers; the address of these registers is called an I/O port. The port numbers are determined not by the processor but by the system's address decoder.
  • On the 8086 a port is accessed only with IN and OUT. Data passes only through AL (byte) or AX (word). A port from 0 to 255 is given in the instruction as a constant; a larger one is given in DX. The word form uses ports n and n + 1 together.
  • Port-mapped I/O uses a separate 64 K address space (M/IO̅ = 0); in memory-mapped I/O the device is at memory addresses and is reached with every memory instruction (for example the B800h text screen).
  • There are three ways of coordinating with a device: polling (the processor reads the status bit in a loop), interrupts (the device alerts the processor), and DMA (a controller moves the data without the processor).
  • The 8255 PPI has three 8-bit ports and a control register. A control word with D7 = 1 sets the mode and direction of the ports (1 = input); a bit set/reset word with D7 = 0 changes a single bit of C.
  • In the traffic lights each lamp is a bit of the word at port 4 (pole k: red 3k, yellow 3k + 1, green 3k + 2). The states are kept in a table and written to the port in turn using SI.
  • INT 15h/86h waits CX:DX microseconds. The delay of MOV CX, N / LOOP is 17N − 8 clock cycles and depends on the clock speed; N = 281 for 1 ms at 4.77 MHz.
  • In the emu8086 stepper motor, bits 0–2 carry the magnets and bit 7 the ready information. The program polls bit 7 before every byte and reads the table with [BX][SI].
  • A real unipolar motor is driven through a driver such as the ULN2003; there are single-phase, two-phase, and half-step sequences. The motor is open loop and its speed is set by the step interval.
  • The LED display shows the word at port 199 as a signed decimal. On a 7-segment display the code is fetched from a table with XLAT; for a common anode the code is inverted. In multiplexed scanning all digits are blanked before switching digits.
  • Because the thermostat can read negative temperatures it uses signed jumps (JL, JLE, JG); unsigned jumps take negative values for large positive numbers.
  • Characters are sent to the printer with INT 21h/05h; LF, CR, HT, and FF control the paper and head. The length is computed at assembly time with offset msg_end - offset msg.
  • The robot works with command, data, and status ports; because the wait routines overwrite AL, the command is saved on the stack before the call.

10.2.13Key terms

  • peripheral
  • I/O port
  • port-mapped / memory-mapped I/O
  • address decoder
  • polling
  • handshaking
  • interrupt
  • direct memory access (DMA)
  • programmable peripheral interface (8255 PPI)
  • control word
  • software delay
  • clock cycle
  • stepper motor
  • seven-segment display
  • segment (display)
  • control character
  • emulator

10.2.14Test Yourself

  1. What is the port 4 word that lights red + yellow on the lower-right and upper-left poles and only red on the other two poles?

    Answer

    Lower right: bits 0 and 1; upper right: bit 3; upper left: bits 6 and 7; lower left: bit 9. The total is 1 + 2 + 8 + 64 + 128 + 512 = 715 = 0000 0010 1100 1011b = 02CBh.

  2. What must CX and DX be to wait 3 seconds with INT 15h/86h?

    Answer

    3,000,000 µs = 002DC6C0h: CX = 002Dh, DX = C6C0h. Because the DX value starts with a letter, it is written 0C6C0h in the source.

  3. Why does IN AL, 300h not assemble? How is the same job written?

    Answer

    In the constant-port form the port number is written in a single byte, and 300h does not fit in this byte. The correct form is MOV DX, 300h · IN AL, DX.

  4. What happens to the ports if 9Bh is written to the control register of the 8255? What is the bit set/reset word that sets PC4 to 1?

    Answer

    9Bh = 1 00 1 1 0 1 1b: mode 0, A input, C upper input, B input, C lower input; all ports are inputs. For PC4 = 1, D3–D1 = 100 and D0 = 1: 0000 1001b = 09h.

  5. On a 4.77 MHz 8086 how long does mov cx, 500 / wait: loop wait take?

    Answer

    17 · 500 − 8 = 8,492 clock cycles; 8,492 ÷ 4.77 ≈ 1,780 µs ≈ 1.78 ms.

  6. What are the common-cathode and common-anode segment codes of the letter 'E'?

    Answer

    For 'E', a, d, e, f, and g light: bits 0, 3, 4, 5, 6. Common cathode 0111 1001b = 79h, common anode 1000 0110b = 86h.

  7. In the thermostat program, if the temperature read is exactly 80 °C, which jump is taken and what happens to the heater?

    Answer

    The result of CMP AL, 60 is positive and JL does not jump. The result of CMP AL, 80 is zero: ZF = 1 and JLE ok jumps. The heater is not touched; it stays in its previous state.

  8. The robot's status port returns 06h. What do the wait_ready and wait_data routines do?

    Answer

    06h = 0000 0110b: bit 1 (busy) and bit 2 (error) are 1, bit 0 (data) is 0. wait_ready keeps waiting because the busy bit is 1; wait_data also waits because the data bit is 0. Neither routine looks at the error bit.

  9. On the test device with 7Fh entered for port 110, IN AL, 110 · INC AL runs. What are AL and OF, SF, ZF?

    Answer

    AL = 80h. One more than +127 appears as −128 in 8 bits: OF = 1, SF = 1, ZF = 0. INC does not touch CF.

  10. If the status register of a memory-mapped device were at B800:0010, which instructions would be enough to wait for bit 7?

    Answer

    After setting ES = B800h: wait: TEST BYTE PTR ES:[0010h], 80h · JZ wait. With a memory-mapped device TEST is applied directly to the memory operand; there is no need to read into AL.

10.2.15Further reading

  • Barry B. Brey, The Intel Microprocessors, 8th edition: the basic I/O interface chapter covers IN/OUT, address decoding, the 8255, and driving 7-segment displays, with circuit diagrams.
  • Intel, 8255A Programmable Peripheral Interface datasheet: timing diagrams for modes 0, 1, and 2 and the original definition of the control word.
  • Texas Instruments, ULN2003A datasheet: the current limits of the Darlington channels and how to wire the COM pin with inductive loads.
  • emu8086 help documentation, I/O ports and hardware interrupts and virtual devices: the port layout and sample programs of the virtual devices.

10.2.16References

  1. emu8086 help documentation: I/O ports and hardware interrupts, Virtual devices, and the sample programs (traffic_lights.asm, stepper_motor.asm, led_display_test.asm, thermometer.asm, printer.asm, robot.asm).
  2. Intel, The 8086 Family User's Manual, 1979 (IN/OUT instructions, the I/O address space, and instruction timings).
  3. Intel, 8255A Programmable Peripheral Interface datasheet.
  4. Texas Instruments, ULN2003A datasheet.
  5. M. Bodur, Mikroişlemcilere Giriş: Assembler ile Yazılım ve Arayüz, EMO, 2014.
  6. R. Brown, Ralf Brown's Interrupt List (INT 15h/86h, INT 21h/05h, INT 16h/00h).
  7. B. B. Brey, The Intel Microprocessors, 8th edition, Pearson, 2009, Chapter 11 (Basic I/O interface).

Related pages: Chapter 10.2 slides · © Sercan Külcü. All rights reserved.