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
INandOUT, 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.
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.
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.
| Device | Port(s) | Direction | Data |
|---|---|---|---|
| Traffic lights | 4 | OUT | word: 12 lamp bits |
| Stepper motor | 7 | OUT / IN | bits 0–2 magnets, bit 7 ready |
| Robot | 9, 10, 11 | OUT / IN | command, data, status |
| Test device (simple io test) | 110, 112 | IN / OUT | byte (110), word (112) |
| Thermometer and heater | 125, 127 | IN / OUT | temperature, heater on/off |
| Printer | 130 | OUT | character (via INT 21h/05h) |
| LED display | 199 | OUT | word: 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.
| Form | Meaning | Port range | Machine code | Clock cycles |
|---|---|---|---|---|
IN AL, port | read 1 byte from the port | 0–255 (constant) | E4 pp | 10 |
IN AX, port | read 1 word from the port | 0–255 (constant) | E5 pp | 10 |
IN AL, DX / IN AX, DX | port number in DX | 0–65.535 | EC / ED | 8 |
OUT port, AL / OUT port, AX | write to the port | 0–255 (constant) | E6 pp / E7 pp | 10 |
OUT DX, AL / OUT DX, AX | port number in DX | 0–65.535 | EE / EF | 8 |
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.
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.
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 ← 5AhThe 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.
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.
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'
retThe 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.
| Step | Instruction | AX | ES | DI | Written to memory | Explanation |
|---|---|---|---|---|---|---|
| 1 | mov ax, 0B800h | B800h | 0700h | 0000h | the segment value goes through a general register first | |
| 2 | mov es, ax | B800h | B800h | 0000h | ES = B800h: text screen memory | |
| 3 | mov di, 0 | B800h | B800h | 0000h | first cell: row 0, column 0 | |
| 4 | mov al, 'A' | B841h | B800h | 0000h | AL = 41h ('A') | |
| 5 | mov ah, 1Eh | 1E41h | B800h | 0000h | AH = 1Eh: blue background, yellow text | |
| 6 | mov es:[di], ax | 1E41h | B800h | 0000h | B800:0000 ← 41h, B800:0001 ← 1Eh | one MOV: character and attribute; a colored A appears on the screen |
| 7 | mov byte ptr es:[di+2], 'B' | 1E41h | B800h | 0000h | B800:0002 ← 42h | character byte of the second cell; the attribute (07h) is preserved |
| 8 | ret | 1E41h | B800h | 0000h | the 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.
| Feature | Port-mapped | Memory-mapped |
|---|---|---|
| Address space | separate, 64 K (0000h–FFFFh) | shared with memory, part of the 1 MB |
| Instructions | IN, OUT only | MOV, ADD, CMP, TEST, AND … |
| Data register | AL / AX only | any register or a constant |
| Addressing | constant (0–255) or DX | all memory addressing modes |
| Memory lost | none | the addresses the device occupies |
| 8086 signal | M/IO̅ = 0 | M/IO̅ = 1 |
| Example | emu8086 devices, 8255, 8259A | B800h 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.
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 againTEST 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.
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.
| Method | Who waits? | Who moves the data? | Suited to |
|---|---|---|---|
| Polling | the processor, in a loop | the processor (IN/OUT) | a single device, simple embedded system |
| Interrupt | nobody; the device signals | the processor (in the service routine) | keyboard, serial line, timer |
| DMA | nobody; the controller takes the bus | DMA 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.
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.
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.
| A1 A0 | Register | Address |
|---|---|---|
| 0 0 | port A | 310h |
| 0 1 | port B | 311h |
| 1 0 | port C | 312h |
| 1 1 | control register | 313h |
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.
| D7 | D6 D5 | D4 | D3 | D2 | D1 | D0 |
|---|---|---|---|---|---|---|
| 1 = mode set | group A mode (00 = mode 0) | port A | PC7–PC4 | group B mode (0 = mode 0) | port B | PC3–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.
Required: port A output (drives LEDs or relays), port B input (switches are read), both halves of C output, all in mode 0.
- D7 = 1: this is a mode set word.
- D6 D5 = 00 and D2 = 0: both groups in mode 0.
- D4 = 0 (A output), D3 = 0 (C upper output), D1 = 1 (B input), D0 = 0 (C lower output).
- 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.
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".
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
retEvery 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.
| Step | Instruction | DX | AL | I/O | Explanation |
|---|---|---|---|---|---|
| 1 | mov dx, 313h | 0313h | 00h | DX = 313h: the address of the control register; kept in DX because it is above 255 | |
| 2 | mov al, 82h | 0313h | 82h | AL = 82h = 1000 0010b: mode 0; A output, C upper output, B input, C lower output | |
| 3 | out dx, al | 0313h | 82h | 313h ← 82h | the control word has been written to the chip; the port directions now follow 82h |
| 4 | mov dx, 311h | 0311h | 82h | DX = 311h: port B | |
| 5 | in al, dx | 0311h | 96h | 311h → 96h | switches read: AL = 96h = 1001 0110b |
| 6 | mov dx, 310h | 0310h | 96h | DX = 310h: port A | |
| 7 | out dx, al | 0310h | 96h | 310h ← 96h | the LEDs copy the switches: bits 7, 4, 2, and 1 light up |
| 8 | mov dx, 313h | 0313h | 96h | DX points to the control register again | |
| 9 | mov al, 0Fh | 0313h | 0Fh | AL = 0Fh = 0000 1111b: D7 = 0, so this is a bit set/reset word | |
| 10 | out dx, al | 0313h | 0Fh | 313h ← 0Fh | D3–D1 = 111 (PC7), D0 = 1: only PC7 becomes 1; the directions do not change |
| 11 | ret | 0313h | 0Fh | 0000h popped from the stack → IP; returns to the INT 20h in the PSP | |
| 12 | INT 20h (PSP:0000) | 0313h | 0Fh | the 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).
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.
What word lights only the green lamps in all directions?
- The green lamps are at bits 3k + 2: for k = 0, 1, 2, 3 that is bits 2, 5, 8, 11.
- The word is 2² + 2⁵ + 2⁸ + 2¹¹ = 4 + 32 + 256 + 2048 = 2340.
- 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_1001bThe 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.
| Ad | Hex | Lower right | Upper right | Upper left | Lower left |
|---|---|---|---|---|---|
| situation | 030Ch | green | red | green | red |
| s1 | 069Ah | yellow | red + yellow | yellow | red + yellow |
| s2 | 0861h | red | green | red | green |
| s3 | 0861h | red | green | red | green |
| s4 | 04D3h | red + yellow | yellow | red + yellow | yellow |
| all_red | 0249h | red | red | red | red |
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.
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.
What must CX and DX be for a 5-second wait?
- Convert the time to microseconds: 5 s = 5 × 1,000,000 = 5,000,000 µs.
- 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.
- The remainders are read from last to first: 4C4B40h. Written in 32 bits it is 004C4B40h.
- Split the number in two: CX = 004Ch, DX = 4B40h.
; wait 5 seconds (5 million µs)
mov cx, 4Ch ; 004C4B40h = 5 000 000
mov dx, 4B40h
mov ah, 86h
int 15hThe 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.
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.
| Instruction | Clock cycles |
|---|---|
MOV CX, constant | 4 |
LOOP (CX ≠ 0, jumps) | 17 |
LOOP (CX = 0, falls through) | 5 |
DEC r16 | 2 |
JNZ (taken / not taken) | 16 / 4 |
CALL near / RET near | 19 / 8 |
; ≈ 1 ms delay (4.77 MHz 8086)
mov cx, 281 ; 4 clocks
delay:
loop delay ; 280 × 17 + 1 × 5 clocksIn 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:
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 passOne 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| Step | Instruction | CX | IP | Explanation |
|---|---|---|---|---|
| 1 | mov cx, 4 | 0004h | 0103h | 4 cycles; total 4 |
| 2 | loop delay | 0003h | 0103h | CX = 3 ≠ 0: jumps to the same instruction, 17 cycles; total 21 |
| 3 | loop delay | 0002h | 0103h | CX = 2: 17 cycles; total 38 |
| 4 | loop delay | 0001h | 0103h | CX = 1: 17 cycles; total 55 |
| 5 | loop delay | 0000h | 0105h | CX = 0: falls through, 5 cycles; total 60 = 17 · 4 − 8 |
| 6 | ret | 0000h | 0000h | left 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.
| Step | Instruction | AX | SI | CX | DX | CF | Port 4 | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | mov ax, all_red | 0249h | 0000h | 0000h | 0000h | 0 | — | AX = all_red = 0249h; an EQU constant, takes up no memory |
| 2 | out 4, ax | 0249h | 0000h | 0000h | 0000h | 0 | 0249h | all directions red |
| 3 | mov si, offset situation | 0249h | 0124h | 0000h | 0000h | 0 | 0249h | SI = 0124h: the first word of the table (situation) |
| 4 | mov ax, [si] | 030Ch | 0124h | 0000h | 0000h | 0 | 0249h | AX ← [0124h] = 030Ch |
| 5 | out 4, ax | 030Ch | 0124h | 0000h | 0000h | 0 | 030Ch | the lamps switch to the situation state |
| 6 | mov cx, 4Ch | 030Ch | 0124h | 004Ch | 0000h | 0 | 030Ch | CX = 004Ch: the high word of 5,000,000 µs |
| 7 | mov dx, 4B40h | 030Ch | 0124h | 004Ch | 4B40h | 0 | 030Ch | DX = 4B40h: the low word |
| 8 | mov ah, 86h | 860Ch | 0124h | 004Ch | 4B40h | 0 | 030Ch | AH = 86h: the BIOS wait service; AL is unchanged |
| 9 | int 15h | 860Ch | 0124h | 004Ch | 4B40h | 0 | 030Ch | waits 5 seconds; CF = 0 on success |
| 10 | add si, 2 | 860Ch | 0126h | 004Ch | 4B40h | 0 | 030Ch | SI = 0126h: next state |
| 11 | cmp si, sit_end | 860Ch | 0126h | 004Ch | 4B40h | 1 | 030Ch | 0126h − 012Eh: borrow, CF = 1 |
| 12 | jb next | 860Ch | 0126h | 004Ch | 4B40h | 1 | 030Ch | JB jumps: next |
| 13 | mov ax, [si] | 069Ah | 0126h | 004Ch | 4B40h | 1 | 030Ch | AX ← [0126h] = 069Ah (s1) |
| 14 | out 4, ax | 069Ah | 0126h | 004Ch | 4B40h | 1 | 069Ah | yellow transition state |
| … | wait, SI = 0128h, CMP and JB | |||||||
| 23 | out 4, ax | 0861h | 0128h | 004Ch | 4B40h | 1 | 0861h | s2 = 0861h; side road green |
| … | wait, SI = 012Ah | |||||||
| 32 | out 4, ax | 0861h | 012Ah | 004Ch | 4B40h | 1 | 0861h | s3 = 0861h; the same state lasts another 5 seconds |
| … | wait, SI = 012Ch | |||||||
| 41 | out 4, ax | 04D3h | 012Ch | 004Ch | 4B40h | 1 | 04D3h | s4 = 04D3h; getting ready to return to the main road |
| … | wait | |||||||
| 46 | add si, 2 | 86D3h | 012Eh | 004Ch | 4B40h | 0 | 04D3h | SI = 012Eh = sit_end |
| 47 | cmp si, sit_end | 86D3h | 012Eh | 004Ch | 4B40h | 0 | 04D3h | equal: CF = 0, ZF = 1 |
| 48 | jb next | 86D3h | 012Eh | 004Ch | 4B40h | 0 | 04D3h | JB falls through: the table is finished |
| 49 | mov si, offset situation | 86D3h | 0124h | 004Ch | 4B40h | 0 | 04D3h | SI goes back to the start of the table |
| 50 | jmp next | 86D3h | 0124h | 004Ch | 4B40h | 0 | 04D3h | endless loop |
| 51 | mov ax, [si] | 030Ch | 0124h | 004Ch | 4B40h | 0 | 04D3h | AX ← [0124h] = 030Ch |
| 52 | out 4, ax | 030Ch | 0124h | 004Ch | 4B40h | 0 | 030Ch | situation 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.
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.
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 | Address | Meaning | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|---|
datcw | 0102h | CW half step | 110 | 100 | 011 | 010 |
datccw | 0106h | CCW half step | 011 | 001 | 110 | 010 |
datcw_fs | 010Ah | CW full step | 001 | 011 | 110 | 000 |
datccw_fs | 010Eh | CCW full step | 100 | 110 | 011 | 000 |
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".
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.
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_stepsteps_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.
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 "…".
| Step | Instruction | AL | BX | SI | CX | ZF | CF | Port 7 | Explanation |
|---|---|---|---|---|---|---|---|---|---|
| 1 | jmp start | 00h | 0000h | 0000h | 0000h | 0 | 0 | — | jumps over the data tables |
| 2 | mov bx, offset datcw | 00h | 0102h | 0000h | 0000h | 0 | 0 | — | BX = 0102h: datcw (clockwise half step) |
| 3 | mov si, 0 | 00h | 0102h | 0000h | 0000h | 0 | 0 | — | SI = 0: position in the table |
| 4 | mov cx, 0 | 00h | 0102h | 0000h | 0000h | 0 | 0 | — | CX = 0: round counter |
| 5 | wait: in al, 7 | 00h | 0102h | 0000h | 0000h | 0 | 0 | — | AL = 00h: bit 7 = 0, motor busy |
| 6 | test al, 10000000b | 00h | 0102h | 0000h | 0000h | 1 | 0 | — | 00h AND 80h = 0: ZF = 1 |
| 7 | jz wait | 00h | 0102h | 0000h | 0000h | 1 | 0 | — | ZF = 1: read again |
| 8 | wait: in al, 7 | 80h | 0102h | 0000h | 0000h | 1 | 0 | — | AL = 80h: motor ready |
| 9 | test al, 10000000b | 80h | 0102h | 0000h | 0000h | 0 | 0 | — | 80h AND 80h ≠ 0: ZF = 0 |
| 10 | jz wait | 80h | 0102h | 0000h | 0000h | 0 | 0 | — | does not jump: a byte will be sent |
| 11 | mov al, [bx][si] | 06h | 0102h | 0000h | 0000h | 0 | 0 | — | AL ← [0102h + 0] = 06h = 110b |
| 12 | out 7, al | 06h | 0102h | 0000h | 0000h | 0 | 0 | 06h | magnets 2 and 1 on: half step (11.25°) |
| 13 | inc si | 06h | 0102h | 0001h | 0000h | 0 | 0 | 06h | SI = 1 |
| 14 | cmp si, 4 | 06h | 0102h | 0001h | 0000h | 0 | 1 | 06h | 1 − 4: CF = 1 |
| 15 | jb next_step | 06h | 0102h | 0001h | 0000h | 0 | 1 | 06h | JB jumps: next byte |
| … | the ready bit is read (80h) | ||||||||
| 19 | mov al, [bx][si] | 04h | 0102h | 0001h | 0000h | 0 | 0 | 06h | AL ← [0103h] = 04h = 100b |
| 20 | out 7, al | 04h | 0102h | 0001h | 0000h | 0 | 0 | 04h | only magnet 2 on |
| … | SI = 2, polling | ||||||||
| 27 | mov al, [bx][si] | 03h | 0102h | 0002h | 0000h | 0 | 0 | 04h | AL ← [0104h] = 03h = 011b |
| 28 | out 7, al | 03h | 0102h | 0002h | 0000h | 0 | 0 | 03h | magnets 1 and 0 on |
| … | SI = 3, polling | ||||||||
| 35 | mov al, [bx][si] | 02h | 0102h | 0003h | 0000h | 0 | 0 | 03h | AL ← [0105h] = 02h = 010b |
| 36 | out 7, al | 02h | 0102h | 0003h | 0000h | 0 | 0 | 02h | only magnet 1 on: the first round is finished |
| 37 | inc si | 02h | 0102h | 0004h | 0000h | 0 | 0 | 02h | SI = 4 |
| 38 | cmp si, 4 | 02h | 0102h | 0004h | 0000h | 1 | 0 | 02h | 4 − 4 = 0: ZF = 1, CF = 0 |
| 39 | jb next_step | 02h | 0102h | 0004h | 0000h | 1 | 0 | 02h | JB does not jump |
| 40 | mov si, 0 | 02h | 0102h | 0000h | 0000h | 1 | 0 | 02h | SI = 0: back to the start of the table |
| 41 | inc cx | 02h | 0102h | 0000h | 0001h | 0 | 0 | 02h | CX = 1: one round (4 bytes) complete |
| 42 | cmp cx, steps_before_direction_change | 02h | 0102h | 0000h | 0001h | 0 | 1 | 02h | 1 − 20h: CF = 1 |
| 43 | jb next_step | 02h | 0102h | 0000h | 0001h | 0 | 1 | 02h | jumps: 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.
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.
| Drive | Port A sequence | Property |
|---|---|---|
| Single phase (wave), full step | 01h 02h 04h 08h | one winding half at a time; least current |
| Two phase, full step | 03h 06h 0Ch 09h | two winding halves at a time; higher torque |
| Half step | 01h 03h 02h 06h 04h 0Ch 08h 09h | mixes 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 6The 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.
| Step | Instruction | pos | BX | AL | SP | Port A | Explanation |
|---|---|---|---|---|---|---|---|
| 1 | inc pos | 0007h | 0000h | 00h | FFFEh | — | the word in memory 6 → 7 |
| 2 | mov bx, pos | 0007h | 0007h | 00h | FFFEh | — | BX ← pos = 7 |
| 3 | and bx, 7 | 0007h | 0007h | 00h | FFFEh | — | the index stays in the range 0–7: 7 |
| 4 | mov al, half[bx] | 0007h | 0007h | 09h | FFFEh | — | AL ← half[7] = 09h = 1001b: B̅ and A |
| 5 | mov dx, 310h | 0007h | 0007h | 09h | FFFEh | — | DX = 310h: 8255 port A |
| 6 | out dx, al | 0007h | 0007h | 09h | FFFEh | 09h | the windings are driven: the field lies between A and B̅ |
| 7 | call delay | 0007h | 0007h | 09h | FFFCh | 09h | return address (0116h) onto the stack: SP = FFFCh |
| 8 | delay: ret | 0007h | 0007h | 09h | FFFEh | 09h | the delay routine is just RET here |
| 9 | jmp fwd | 0007h | 0007h | 09h | FFFEh | 09h | next step |
| 10 | inc pos | 0008h | 0007h | 09h | FFFEh | 09h | pos = 8 |
| 11 | mov bx, pos | 0008h | 0008h | 09h | FFFEh | 09h | BX = 8 |
| 12 | and bx, 7 | 0008h | 0000h | 09h | FFFEh | 09h | 8 AND 7 = 0: the sequence wraps around |
| 13 | mov al, half[bx] | 0008h | 0000h | 01h | FFFEh | 09h | AL ← half[0] = 01h: only A |
| … | DX = 310h | ||||||
| 15 | out dx, al | 0008h | 0000h | 01h | FFFEh | 01h | the field returns to winding A: one half step |
| … | CALL, RET, JMP | ||||||
| 19 | inc pos | 0009h | 0000h | 01h | FFFEh | 01h | pos = 9 |
| 20 | mov bx, pos | 0009h | 0009h | 01h | FFFEh | 01h | BX = 9 |
| 21 | and bx, 7 | 0009h | 0001h | 01h | FFFEh | 01h | 9 AND 7 = 1 |
| 22 | mov al, half[bx] | 0009h | 0001h | 03h | FFFEh | 01h | AL ← half[1] = 03h: A and B |
| … | DX = 310h | ||||||
| 24 | out dx, al | 0009h | 0001h | 03h | FFFEh | 03h | the 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.
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.
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 runsThe 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.
| Step | Instruction | AX | Display | Explanation |
|---|---|---|---|---|
| 1 | mov ax, 1234 | 04D2h | — | 1234 = 04D2h |
| 2 | out 199, ax | 04D2h | 1234 | 1234 on the display |
| 3 | mov ax, -5678 | E9D2h | 1234 | −5678 = 10000h − 162Eh = E9D2h |
| 4 | out 199, ax | E9D2h | −5678 | the display reads the word as signed: −5678 |
| 5 | mov ax, 0 | 0000h | −5678 | counter 0 |
| 6 | out 199, ax | 0000h | 0 | 0 on the display |
| 7 | inc ax | 0001h | 0 | AX = 1 |
| 8 | jmp x1 | 0001h | 0 | back to x1; HLT is never reached |
| 9 | out 199, ax | 0001h | 1 | 1 on the display |
| 10 | inc ax | 0002h | 1 | AX = 2 |
| 11 | jmp x1 | 0002h | 1 | loop |
| 12 | out 199, ax | 0002h | 2 | 2 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).
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.
| Digit | Segments lit | Common cathode (CC) | Common anode (CA) |
|---|---|---|---|
| 0 | a b c d e f | 3Fh | C0h |
| 1 | b c | 06h | F9h |
| 2 | a b d e g | 5Bh | A4h |
| 3 | a b c d g | 4Fh | B0h |
| 4 | b c f g | 66h | 99h |
| 5 | a c d f g | 6Dh | 92h |
| 6 | a c d e f g | 7Dh | 82h |
| 7 | a b c | 07h | F8h |
| 8 | a b c d e f g | 7Fh | 80h |
| 9 | a b c d f g | 6Fh | 90h |
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,6FhIn 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.
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, 08hThe 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, 08hBX 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.
| Step | Instruction | SI | AL | Port A | Port C | Explanation |
|---|---|---|---|---|---|---|
| 1 | mov bx, offset segtab | 0000h | 00h | — | — | BX = 0124h: the start of the code table |
| 2 | mov si, 0 | 0000h | 00h | — | — | SI = 0: first position |
| 3 | mov dx, 312h | 0000h | 00h | — | — | DX = 312h: port C, digit select |
| 4 | mov al, 0 | 0000h | 00h | — | — | AL = 0 |
| 5 | out dx, al | 0000h | 00h | — | 00h | all digits blank: no ghosting |
| 6 | mov al, digits[si] | 0000h | 02h | — | 00h | AL ← digits[0] = 2 |
| 7 | xlat | 0000h | 5Bh | — | 00h | AL ← [BX + 2] = 5Bh |
| 8 | mov dx, 310h | 0000h | 5Bh | — | 00h | DX = 310h: port A, segments |
| 9 | out dx, al | 0000h | 5Bh | 5Bh | 00h | the segment code goes out on the port |
| 10 | mov al, select[si] | 0000h | 01h | 5Bh | 00h | AL ← select[0] = 01h |
| 11 | mov dx, 312h | 0000h | 01h | 5Bh | 00h | DX = 312h |
| 12 | out dx, al | 0000h | 01h | 5Bh | 01h | only position 1 lit: "2" |
| 13 | inc si | 0001h | 01h | 5Bh | 01h | SI = 1 |
| … | CMP, JB; position 2: port C ← 00h, digit 0 | |||||
| 20 | xlat | 0001h | 3Fh | 5Bh | 00h | XLAT: AL = 3Fh |
| 22 | out dx, al | 0001h | 3Fh | 3Fh | 00h | port A ← 3Fh |
| 25 | out dx, al | 0001h | 02h | 3Fh | 02h | only position 2 lit: "0" |
| … | position 3: digit 2 | |||||
| 33 | xlat | 0002h | 5Bh | 3Fh | 00h | XLAT: AL = 5Bh |
| 38 | out dx, al | 0002h | 04h | 5Bh | 04h | only position 3 lit: "2" |
| … | position 4: digit 6 | |||||
| 46 | xlat | 0003h | 7Dh | 5Bh | 00h | XLAT: AL = 7Dh |
| 51 | out dx, al | 0003h | 08h | 7Dh | 08h | only position 4 lit: "6" |
| 52 | inc si | 0004h | 08h | 7Dh | 08h | SI = 4 |
| 53 | cmp si, 4 | 0004h | 08h | 7Dh | 08h | equal: CF = 0 |
| 54 | jb next_dig | 0004h | 08h | 7Dh | 08h | the loop ends |
| 55 | ret | 0004h | 08h | 7Dh | 08h | in 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.
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 loopThe 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.
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.
| Step | Instruction | AL | ZF | SF | OF | CF | Heater | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | mov ax, cs | 00h | 0 | 0 | 0 | 0 | off | AX = CS = 0700h |
| 2 | mov ds, ax | 00h | 0 | 0 | 0 | 0 | off | DS = 0700h; a constant cannot be written directly into a segment register |
| 3 | in al, 125 | 37h | 0 | 0 | 0 | 0 | off | 55 °C = 37h |
| 4 | cmp al, 60 | 37h | 0 | 1 | 0 | 1 | off | 55 − 60 = −5: SF = 1, OF = 0 |
| 5 | jl low | 37h | 0 | 1 | 0 | 1 | off | SF ≠ OF: jumps (low) |
| 6 | mov al, 1 | 01h | 0 | 1 | 0 | 1 | off | AL = 1 |
| 7 | out 127, al | 01h | 0 | 1 | 0 | 1 | on | the heater is switched on |
| 8 | jmp ok | 01h | 0 | 1 | 0 | 1 | on | jump to ok |
| 9 | jmp start | 01h | 0 | 1 | 0 | 1 | on | new measurement |
| 10 | in al, 125 | 46h | 0 | 1 | 0 | 1 | on | 70 °C = 46h |
| 11 | cmp al, 60 | 46h | 0 | 0 | 0 | 0 | on | 70 − 60 = 10: SF = 0, OF = 0 |
| 12 | jl low | 46h | 0 | 0 | 0 | 0 | on | SF = OF: does not jump |
| 13 | cmp al, 80 | 46h | 0 | 1 | 0 | 1 | on | 70 − 80 = −10: SF = 1, ZF = 0 |
| 14 | jle ok | 46h | 0 | 1 | 0 | 1 | on | ZF = 1 or SF ≠ OF: jumps; the heater is left alone |
| 15 | jmp start | 46h | 0 | 1 | 0 | 1 | on | new measurement |
| 16 | in al, 125 | 55h | 0 | 1 | 0 | 1 | on | 85 °C = 55h |
| 17 | cmp al, 60 | 55h | 0 | 0 | 0 | 0 | on | 85 − 60 = 25 |
| 18 | jl low | 55h | 0 | 0 | 0 | 0 | on | does not jump |
| 19 | cmp al, 80 | 55h | 0 | 0 | 0 | 0 | on | 85 − 80 = 5: SF = 0, ZF = 0 |
| 20 | jle ok | 55h | 0 | 0 | 0 | 0 | on | does not jump |
| 21 | jg high | 55h | 0 | 0 | 0 | 0 | on | ZF = 0 and SF = OF: jumps (high) |
| 22 | mov al, 0 | 00h | 0 | 0 | 0 | 0 | on | AL = 0 |
| 23 | out 127, al | 00h | 0 | 0 | 0 | 0 | off | the heater is switched off |
| 24 | jmp start | 00h | 0 | 0 | 0 | 0 | off | new 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.
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).
| Kod | Ad | Effect |
|---|---|---|
| 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.
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:
"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
retTo 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.
| Step | Instruction | CX | DL | SI | To printer | Explanation |
|---|---|---|---|---|---|---|
| 1 | jmp start | 0000h | 00h | 0000h | jumps over the data bytes to 015Fh | |
| 2 | mov dl, 12 | 0000h | 0Ch | 0000h | DL = 12 = 0Ch: form feed | |
| 3 | mov ah, 5 | 0000h | 0Ch | 0000h | AH = 05h: DOS printer output | |
| 4 | int 21h | 0000h | 0Ch | 0000h | FF | the printer moves to a new page |
| 5 | mov si, offset msg | 0000h | 0Ch | 0102h | SI = 0102h: msg | |
| 6 | mov cx, offset msg_end - offset msg | 003Bh | 0Ch | 0102h | 013Dh − 0102h = 3Bh = 59 characters | |
| 7 | mov dl, [si] | 003Bh | 48h | 0102h | DL ← [0102h] = 'H' | |
| 8 | mov ah, 5 | 003Bh | 48h | 0102h | AH = 05h | |
| 9 | int 21h | 003Bh | 48h | 0102h | 'H' | 'H' goes to the printer |
| 10 | inc si | 003Bh | 48h | 0103h | SI = 0103h | |
| 11 | loop print | 003Ah | 48h | 0103h | CX = 58 ≠ 0: back to print | |
| … | continues character by character | |||||
| 84 | int 21h | 002Ch | 0Ah | 0111h | LF | byte 16: LF, the paper advances one line |
| 89 | int 21h | 002Bh | 0Dh | 0112h | CR | byte 17: CR, start of line |
| … | 15 asterisks | |||||
| 169 | int 21h | 001Bh | 0Dh | 0122h | CR | byte 33: CR; no LF, so the head returns to the start of the same line |
| 174 | int 21h | 001Ah | 09h | 0123h | HT | byte 34: HT, jumps to the eight-column tab stop |
| … | "Have a nice printing day" is printed over the asterisks | |||||
| 297 | mov dl, [si] | 0001h | 21h | 013Ch | DL ← [013Ch] = '!' | |
| 299 | int 21h | 0001h | 21h | 013Ch | '!' | last character |
| 300 | inc si | 0001h | 21h | 013Dh | SI = 013Dh = msg_end | |
| 301 | loop print | 0000h | 21h | 013Dh | CX = 0: the loop ends | |
| 302 | mov dx, offset msg2 | 0000h | 3Eh | 013Dh | DX = address of msg2 (013Eh) | |
| 304 | int 21h | 0000h | 3Eh | 013Dh | message on screen (up to the $) | |
| 306 | int 16h | 0000h | 3Eh | 013Dh | waits for a key | |
| 309 | int 21h | 0000h | 0Ch | 013Dh | FF | last form feed: the paper is ejected |
| 310 | ret | 0000h | 0Ch | 013Dh | the 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.
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.
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).
| Command | Effect | Data | Ahead |
|---|---|---|---|
| 0 | do nothing | 255 (FFh) | wall |
| 1 | move forward | 0 | empty |
| 2 | turn left | 7 | lit lamp |
| 3 | turn right | 8 | unlit lamp |
| 4 | examine what is ahead | ||
| 5 | turn the lamp on | ||
| 6 | turn the lamp off |
| Bit | If 1 |
|---|---|
| bit 0 | new data in the data register |
| bit 1 | robot busy (command in progress) |
| bit 2 | error 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 ENDPThe 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).
| Step | Instruction | AL | SP | ZF | Port 9 | Explanation |
|---|---|---|---|---|---|---|
| 1 | main_loop: CALL wait_ready | 00h | FFFCh | 0 | — | return address 0103h onto the stack |
| 2 | b1: IN AL, 11 | 00h | FFFCh | 0 | — | status = 00h |
| 3 | TEST AL, 010b | 00h | FFFCh | 1 | — | bit 1 = 0: not busy, ZF = 1 |
| 4 | JNZ b1 | 00h | FFFCh | 1 | — | does not jump |
| 5 | RET | 00h | FFFEh | 1 | — | return: SP = FFFEh |
| 6 | MOV AL, 4 | 04h | FFFEh | 1 | — | command 4: examine |
| 7 | OUT 9, AL | 04h | FFFEh | 1 | 04h | the robot examines what is ahead |
| 8 | CALL wait_data | 04h | FFFCh | 1 | 04h | waits for data |
| 9 | v1: IN AL, 11 | 01h | FFFCh | 1 | 04h | status = 01h: new data available |
| 10 | TEST AL, 001b | 01h | FFFCh | 0 | 04h | bit 0 = 1: ZF = 0 |
| 11 | JZ v1 | 01h | FFFCh | 0 | 04h | does not jump |
| 12 | RET | 01h | FFFEh | 0 | 04h | return |
| 13 | IN AL, 10 | FFh | FFFEh | 0 | 04h | data = FFh: wall |
| 14 | CMP AL, 0FFh | FFh | FFFEh | 1 | 04h | equal: ZF = 1 |
| 15 | JE turn | FFh | FFFEh | 1 | 04h | jumps to turn |
| 16 | turn: MOV AL, 3 | 03h | FFFEh | 1 | 04h | command 3: turn right |
| 17 | JMP send | 03h | FFFEh | 1 | 04h | send |
| 18 | send: PUSH AX | 03h | FFFCh | 1 | 04h | AX = 0003h onto the stack: SP = FFFCh |
| 19 | CALL wait_ready | 03h | FFFAh | 1 | 04h | return address onto the stack: SP = FFFAh |
| 20 | b1: IN AL, 11 | 03h | FFFAh | 1 | 04h | status = 03h: AL overwritten |
| 21 | TEST AL, 010b | 03h | FFFAh | 0 | 04h | bit 1 = 1: busy, ZF = 0 |
| 22 | JNZ b1 | 03h | FFFAh | 0 | 04h | read again |
| 23 | b1: IN AL, 11 | 01h | FFFAh | 0 | 04h | status = 01h |
| 24 | TEST AL, 010b | 01h | FFFAh | 1 | 04h | bit 1 = 0: ZF = 1 |
| 25 | JNZ b1 | 01h | FFFAh | 1 | 04h | does not jump |
| 26 | RET | 01h | FFFCh | 1 | 04h | return: SP = FFFCh, AL = 01h |
| 27 | POP AX | 03h | FFFEh | 1 | 04h | AL = 03h is back |
| 28 | OUT 9, AL | 03h | FFFEh | 1 | 03h | "turn right" goes to the robot |
| 29 | JMP main_loop | 03h | FFFEh | 1 | 03h | the 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.
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.
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
retWhen 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.
| Step | Instruction | AX | ZF | SF | OF | CF | I/O | Explanation |
|---|---|---|---|---|---|---|---|---|
| 1 | in al, 110 | 00FFh | 0 | 0 | 0 | 0 | 110 → FFh | byte read: AL = FFh |
| 2 | inc al | 0000h | 1 | 0 | 0 | 0 | FFh + 1 = 00h: ZF = 1; INC does not touch CF | |
| 3 | out 110, al | 0000h | 1 | 0 | 0 | 0 | 110 ← 00h | port 110 = 00h in the window |
| 4 | in ax, 112 | 7FFFh | 1 | 0 | 0 | 0 | 112 → 7FFFh | word read: AL ← port 112, AH ← port 113 |
| 5 | add ax, 1 | 8000h | 0 | 1 | 1 | 0 | 7FFFh + 1 = 8000h: the sum of two positives is negative, OF = 1 | |
| 6 | out 112, ax | 8000h | 0 | 1 | 1 | 0 | 112 ← 8000h | port 112 = 8000h in the window |
| 7 | ret | 8000h | 0 | 1 | 1 | 0 | 0000h popped from the stack → IP | |
| 8 | INT 20h (PSP:0000) | 8000h | 0 | 1 | 1 | 0 | the 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).
| Device | Port | Basic idea |
|---|---|---|
| Traffic lights | 4 | Each bit is a lamp; state table and INT 15h/86h wait. |
| Stepper motor | 7 | Bits 0–2 magnets, bit 7 ready; half step 11.25°, full step 22.5°. |
| LED display | 199 | Word, signed decimal display. |
| Thermometer | 125, 127 | Read, signed comparison, heater on/off. |
| Printer | 130 | INT 21h/05h; control characters LF, CR, HT, FF. |
| Robot | 9, 10, 11 | Command, data, status; poll the busy and data bits. |
| Test device | 110, 112 | Byte and word I/O experiment. |
| 8255 PPI (real) | 310h–313h | The 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", 12The 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
INandOUT. 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/LOOPis 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
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.
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
0C6C0hin the source.Why does
IN AL, 300hnot 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.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.
On a 4.77 MHz 8086 how long does
mov cx, 500/wait: loop waittake?Answer
17 · 500 − 8 = 8,492 clock cycles; 8,492 ÷ 4.77 ≈ 1,780 µs ≈ 1.78 ms.
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.
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, 60is positive andJLdoes not jump. The result ofCMP AL, 80is zero: ZF = 1 andJLE okjumps. The heater is not touched; it stays in its previous state.The robot's status port returns 06h. What do the
wait_readyandwait_dataroutines do?Answer
06h = 0000 0110b: bit 1 (busy) and bit 2 (error) are 1, bit 0 (data) is 0.
wait_readykeeps waiting because the busy bit is 1;wait_dataalso waits because the data bit is 0. Neither routine looks at the error bit.On the test device with 7Fh entered for port 110,
IN AL, 110·INC ALruns. 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.
INCdoes not touch CF.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 deviceTESTis 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
- 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).
- Intel, The 8086 Family User's Manual, 1979 (IN/OUT instructions, the I/O address space, and instruction timings).
- Intel, 8255A Programmable Peripheral Interface datasheet.
- Texas Instruments, ULN2003A datasheet.
- M. Bodur, Mikroişlemcilere Giriş: Assembler ile Yazılım ve Arayüz, EMO, 2014.
- R. Brown, Ralf Brown's Interrupt List (INT 15h/86h, INT 21h/05h, INT 16h/00h).
- 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.