Skip to content
ImagineWorld

Communications Breakdown

node_idnode-book_the-secret-life-of-programs_chapter-09-communications-breakdown
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleCommunications Breakdown
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/slp-fig-9-01-cartoon-robot-in-hard-hat-holding-a.png, assets/slp-fig-9-02-circuit-diagram-of-an-avr-microcontroller-with.png, assets/slp-fig-9-03-avr-port-b-construction-circuit-diagram-showing.png, assets/slp-fig-9-04-simple-pushbutton-circuit-with-voltage-source-resistor.png, assets/slp-fig-9-05-two-voltage-vs-time-diagrams-showing-button.png, assets/slp-fig-9-06-diagram-showing-voltage-waveform-with-labeled-events.png, assets/slp-fig-9-07-fir-filter-button-debouncer-diagram-showing-inb.png, assets/slp-fig-9-08-sevensegment-display-diagram-with-labeled-segments-ag.png, assets/slp-fig-9-09-diagram-of-multiplexed-led-displays-connected-to.png, assets/slp-fig-9-10-circuit-diagram-of-multiplexed-buttons-and-displays.png, assets/slp-fig-9-11-table.png, assets/slp-fig-9-12-table.png, assets/slp-fig-9-13-binary-rotary-encoder-with-8-sectors-labeled.png, assets/slp-fig-9-14-binary-rotary-encoder-alignment-error-diagram-with.png, assets/slp-fig-9-15-gray-code-rotary-encoder-wheel-with-numbered.png, assets/slp-fig-9-16-quadrature-waveform-diagram-showing-x-and-y.png, assets/slp-fig-9-17-timing-diagram-showing-bit-07-and-strobe.png, assets/slp-fig-9-18-diagram-of-serial-communications-using-shift-registers.png, assets/slp-fig-9-19-markspace-signaling-timing-diagram-showing-first-and.png, assets/slp-fig-9-20-table.png, assets/slp-fig-9-21-frequency-shift-keying-waveform-for-ascii-letter.png, assets/slp-fig-9-22-digitaltoanalog-converter-using-leds-with-pins-pb0.png, assets/slp-fig-9-23-schematic-of-a-digitaltoanalog-converter-using-leds.png, assets/slp-fig-9-24-dac-schematic-symbol-with-inputs-d0n-and.png, assets/slp-fig-9-25-synthesized-sawtooth-wave-with-c-code-snippet.png, assets/slp-fig-9-26-fifo-memory-diagram-with-data-bus-highwater.png, assets/slp-fig-9-27-sample-and-hold-circuit-diagram-with-analog.png, assets/slp-fig-9-28-analog-comparator-schematic-symbol-with-inputs-and.png, assets/slp-fig-9-29-flash-converter-circuit-with-8-comparators-and.png, assets/slp-fig-9-30-analogtodigital-converter-block-diagram-with-analog-input.png, assets/slp-fig-9-31-table.png, assets/slp-fig-9-32-diagram-of-successive-approximation-adc-operation-showing.png, assets/slp-fig-9-33-adc-schematic-symbol-with-input-vin-and.png, assets/slp-fig-9-34-table.png, assets/slp-fig-9-35-table.png, assets/slp-fig-9-36-table.png, assets/slp-fig-9-37-musical-score-with-treble-clef-44-time.png, assets/slp-fig-9-38-waveform-diagram-showing-d5-b4-g4-sine.png, assets/slp-fig-9-39-table.png, assets/slp-fig-9-40-four-filter-response-curves-low-pass-high.png, assets/slp-fig-9-41-table.png, assets/slp-fig-9-42-table.png, assets/slp-fig-9-43-table.png, assets/slp-fig-9-44-table.png, assets/slp-fig-9-45-three-head-diagrams-labeled-left-center-right.png, assets/slp-fig-9-46-radio-spectrum-diagram-showing-frequency-bands-983.png, assets/slp-fig-9-47-diagram-showing-fm-stereo-signal-generation-with.png, assets/slp-fig-9-48-table.png, assets/slp-fig-9-49-three-rows-showing-image-sampling-at-different.png, assets/slp-fig-9-50-diagram-showing-supersampling-a-pixelated-circle-on.png, assets/slp-fig-9-51-diagram-showing-diagonal-line-movement-across-grid.png, assets/slp-fig-9-52-three-panels-showing-a-stick-figure-approaching.png, assets/slp-fig-9-53-vector-graphics-diagram-showing-a-house-shape.png, assets/slp-fig-9-54-diagram-showing-raster-scan-pattern-with-horizontal.png, assets/slp-fig-9-55-diagram-showing-raster-scan-pattern-with-horizontal.png
local graph

Computers don’t compute just for the thrill of it. They take in input from various sources, do their computations, and produce output for use by a huge range of devices. Computers might be communicating with people, talking to each other, or running factories. Let’s explore this a bit more.

I briefly mentioned input and output (I/O) in “Input and Output” on page 96, referring to getting things into and out of the processor core. Doing that isn’t all that difficult; all we need are some latches (see “Latches” on page 71) for output and tri-state buffers (refer to Figure 2-38) for input. It used to be that each and every aspect of an I/O device would be hooked up to some bit on a latch or buffer, and the computer would be the puppeteer responsible for the articulation of every limb.

Processor cost reduction has changed that. Many formerly complex I/O devices now include their own microprocessors. For example, you can purchase a three-axis accelerometer or temperature sensor that provides a

[!visual-conversion] cartoon robot in hard hat holding a sign with ‘LY … Cropped from the scan (PDF page 181, printed p. 141): cartoon robot in hard hat holding a sign with ‘LY GE’ visible

nice digital output for a few dollars. I won’t bother talking about devices like those because they’re not interesting from a programming standpoint—the interface is just reading and writing bytes as described in the device specification. But that doesn’t get you off the hook. You might work on the code for a device with an integrated processor. If you’re designing the next internet-connected hairbrush, you’ll likely bristle at its hairy control algorithm.

This chapter examines techniques for interacting with some of the I/O devices that are still interesting from a programming standpoint. It also covers sampling, because that’s how we convert real-world analog data into a digital form usable by computers and vice versa.

The simplest forms of I/O involve connecting things to bits that can be read and written by the CPU. These forms began evolving into more complicated devices when they started getting used a lot. This section looks at a few examples.

The easiest way to get a computer to talk to something is to hook it up to an I/O port. For example, Atmel makes the AVR family of small processors. They include a large number of built-in I/O devices. In Figure 6-1, we’re hooking some things up to port B.

[!visual-conversion] Circuit diagram of an AVR microcontroller with Vcc, GND, PB0-PB7 … Cropped from the scan (PDF page 182, printed p. 142): Circuit diagram of an AVR microcontroller with Vcc, GND, PB0-PB7 pins, a switch, and an LED with resistor.

Figure 6-1: Light and switch on port B

You should recognize the switch in Figure 6-1 from Chapter 2. The LED is a light-emitting diode. A diode is a semiconductor device that works like an amusement park turnstile: it lets electricity through only in one direction, indicated by the direction of the hollow arrow. LEDs have the nice side effect that they glow.

Note the resistor in series with the LED. It’s there to limit the amount of current that flows through the LED so that neither it nor PB₀ burns up. You can calculate the resistor value using Ohm’s law, introduced in Chapter 2. Let’s say that V is 5 volts. One of the characteristics of the silicon sandwiches discussed in “Transistors” on page 51 is that the voltage

across one is 0.7 volts. The AVR processor’s datasheet says that the output voltage for a logic 1 when VISV_{IS} is 5 volts is 4.2 volts. We want to limit the current to 10 mA (0.01 A) because that’s what the LED expects; the AVR is capable of 20 mA. Ohm’s law says that resistance is voltage divided by current, so (4.2−0.7)÷0.01=350Ω(4.2 - 0.7) \div 0.01 = 350\Omega . As you can see, PB7PB_7 can be switched between the voltages for 0 and 1. No electricity flows through PB0PB_0 when it’s set to 0. Electricity flows through the LED when PB0PB_0 is 1, making it glow. Make sure that you read the datasheet for any LED or other component that you use, because characteristics such as the voltage drop may be different.

Port B is controlled by three registers, as shown in Figure 6-2. DDRBDDRB , the data direction register, determines whether each pin is an input or an output. PORTBPORTB is a latch that holds the output data. PINBPINB reads the values of the pins.

7 6 5 4 3 2 1 0 DDRB
DDB7 DDB6 DDB5 DDB4 DDB3 DDB2 DDB1 DDB0
7 6 5 4 3 2 1 0 PORTB
PORTB7 PORTB6 PORTB5 PORTB4 PORTB3 PORTB2 PORTB1 PORTB0
7 6 5 4 3 2 1 0 PINB
PINB7 PINB6 PINB5 PINB4 PINB3 PINB2 PINB1 PINB0

Figure 6-2: AVR PORTB registers

This may appear really complicated, but as you can see in Figure 6-3, it’s just another arrangement of our standard building blocks: demultiplexers, flip-flops, and tri-state buffers.

Figure 6-3: AVR port B construction

DDRB is the data direction register for port B. Putting a 1 in any bit turns the associated pin into an output; if set to 0, it’s an input. PORTB is the output part of the port. Writing a 0 or a 1 into any bit makes the

[!visual-conversion] AVR port B construction circuit diagram showing Data bus, Address … Cropped from the scan (PDF page 183, printed p. 143): AVR port B construction circuit diagram showing Data bus, Address bus, R/W, DDRB, PORTB, and PINB connections

associated output a low voltage or a high voltage. Reading PINB supplies the state of the associated pins, so if pins 6 and 0 are pulled high and the rest are pulled low, it’ll read 01000001, or 0x41.

As you can see, it’s pretty easy to get data in and out of the chip. You can read the switch by looking at PINB₇ in the PINB register. You can turn the LED on and off by writing to PORTB₀ in the PORTB register. You could write a simple program to blink the LED for the perpetual entertainment of yourself and all your friends.

Lots of devices have buttons or switches of some sort. They’re not as easy for a computer to read as you might think because of the way they’re designed. A simple push button consists of a pair of electrical contacts and a piece of metal that connects them when the button is pressed. Take a look at the circuit in Figure 6-4.

Figure 6-4: Simple push-button circuit

R is what’s called a pull-up resistor, just like we saw earlier in Figure 2-37. When the button is not pushed, the resistor pulls the voltage on the processor interrupt request (IRQ) pin up to the voltage supplied by V, making it a logic 1. When the button is pressed, the resistor limits the current from V so that it doesn’t burn up, allowing a logic 0 to be presented to IRQ.

Seems simple, but Figure 6-5 shows that it isn’t. You would think that when you pushed and released the button, the signal at IRQ would look like the picture on the left, but it actually looks more like the one on the right.

Figure 6-5: Button bounce

What’s going on here? When the piece of metal connected to the button hits the contacts, it bounces and comes off the contacts for a short time. It might bounce several times before settling down. Since we connected the button to an interrupt-generating pin on the processor, we might get several interrupts from a single button push, which is probably not what we want. We need to debounce the button. (You can get bounce-free buttons, but they often cost more.)

[!visual-conversion] Simple push-button circuit with voltage source, resistor R, and Processor … Cropped from the scan (PDF page 184, printed p. 144): Simple push-button circuit with voltage source, resistor R, and Processor IRQ pin

[!visual-conversion] Two voltage vs. time diagrams showing button press and release … Cropped from the scan (PDF page 184, printed p. 144): Two voltage vs. time diagrams showing button press and release events.

A simple way to debounce is to have the interrupt handler set a timer, and then you test the state of the button after the timer expires, as Figure 6-6 illustrates. We can approach this in two different ways: setting a timer on the first interrupt or replacing an existing timer with a new one on each interrupt.

[!visual-conversion] Diagram showing voltage waveform with labeled events: Press, Test, Release, … Cropped from the scan (PDF page 185, printed p. 145): Diagram showing voltage waveform with labeled events: Press, Test, Release, and Timer.

Figure 6-6: Button debounce timer

This approach works but isn’t necessarily the best one. It’s hard to choose a timer value because button bounce time can change over time due to mechanical wear. You’ve probably had a reviled alarm clock where the buttons were worn to the point that setting the time was difficult. Also, most devices have more than one button, and it’s unlikely that a processor has enough interrupt pins to go around. We could build circuitry to share interrupts, but we’d rather do it cheaply in software. Most systems have some sort of timer that can generate periodic interrupts. We can piggyback on that interrupt for button debouncing.

Let’s assume that we have eight buttons hooked up to some I/O port, such as we saw in Figure 6-1, and that the state of the I/O port is available in a variable named INB that is an 8-bit unsigned char. We can construct a finite impulse response (FIR) filter out of an array, as shown in Figure 6-7. A FIR is a queue; on each timer tick, we discard the oldest element and shift in a new one. We OR the array elements together to form the current state as part of a two-element queue; current is moved to previous before we calculate the new current. All we have to do now is XOR the current and previous states to find out which buttons have changed state.

[!visual-conversion] FIR filter button debouncer diagram showing INB, filter[0], filter[1], filter[2], … Cropped from the scan (PDF page 185, printed p. 145): FIR filter button debouncer diagram showing INB, filter[0], filter[1], filter[2], current, and previous state arrays with bit values and arrows indicating data flow.

Figure 6-7: FIR filter button debouncer

It’s a pretty simple piece of code, as shown in the C programming language in Listing 6-1.

unsigned char filter[FILTER_SIZE];
unsigned char changed;
unsigned char current;
unsigned char previous;
previous = current;
current = 0;
for (int i = FILTER_SIZE - 1; i > 0; i--) {
filter[i] = filter[i - 1];
current |= filter[i];
}
filter[0] = INB;
current |= filter[0];
changed = current ^ previous;

Listing 6-1: FIR button debouncer

FILTER_SIZE is the number of elements in the filter, the choice of which depends on how noisy the buttons are and the timer interrupt rate.

Many widgets have some sort of display. I’m not talking about things with computer screens here—more like alarm clocks and dishwashers. There are often several indicator lights and possibly some simple numeric displays.

A common type of simple indicator is the seven-segment display shown in Figure 6-8. These displays have seven LEDs arranged in a figure-8 pattern plus maybe an additional decimal point.

Figure 6-8: Seven-segment display

The eight LEDs in a display require 16 electrical connections (pins). But that’s not how they’re typically constructed; there’s a pin for one end of each LED and a common connection for the other. Since we only need to control one end to turn an LED on or off, this common connection saves on pins, which reduces cost. Figure 6-8 shows a common cathode display in which the cathodes are all tied together and the anodes each have their own pins.

[!visual-conversion] Seven-segment display diagram with labeled segments A-G and DP, showing … Cropped from the scan (PDF page 186, printed p. 146): Seven-segment display diagram with labeled segments A-G and DP, showing common cathode configuration.

We could just hook up the anodes to output pins on a processor and the cathodes to the ground or negative end of the voltage source or power supply. A high (1) voltage on a pin would light up the corresponding LED. In practice, most processors don’t supply enough current for that to work, so an additional driver circuit is used. Open-collector outputs (shown back in Figure 2-36) are often used.

The software to drive one of these displays is pretty simple. All we need is a table that maps numbers (and maybe letters) to the appropriate segments to light. But it should come as no surprise that there are complications. We rarely have a single display; for example, an alarm clock has four. Though we could hook each display up to its own I/O port, it’s unlikely that there are that many ports. The solution is to multiplex the displays by connecting the anodes to port A and the cathodes to port B, as shown in Figure 6-9.

[!visual-conversion] Diagram of multiplexed LED displays connected to a processor with … Cropped from the scan (PDF page 187, printed p. 147): Diagram of multiplexed LED displays connected to a processor with A0-7 and B0-B3 lines.

Figure 6-9: Multiplexed displays

The display anodes are wired in parallel; all of the A segments are connected together, all of the B segments are connected together, and so on. The cathode connection for each display is connected to its own output pin. A display segment can light up only if its anode is a 1 and its cathode a 0. You might wonder why, for example, segments A and B wouldn’t light up if A were a 1 and B were a 0. Remember that the D in LED stands for diode, and diodes are one-way streets for electricity.

We take advantage of the human persistence of vision to make the displays work. A display doesn’t have to be on all the time for us to perceive it as lit. Our eyes and brain will tell us that it’s lit if it’s on for as little as 1/24 of a second. This is the same effect that makes movies and video work. All we have to do is switch which display is on by setting the associated cathode pin to 0 and the segment anodes to whatever we want to display. We can switch displays in a timer interrupt handler similar to the one we used in the earlier push-button example.

It’s common for devices to include both buttons and displays. As it turns out, we can save some pins by multiplexing the buttons as well as the displays. Let’s say we have a 12-button telephone-style keypad in addition to our four displays, as shown in Figure 6-10.

[!visual-conversion] Circuit diagram of multiplexed buttons and displays with processor pins … Cropped from the scan (PDF page 188, printed p. 148): Circuit diagram of multiplexed buttons and displays with processor pins A0-7, B0-B3, C0-C2.

Figure 6-10: Multiplexed buttons and displays

What have we accomplished with all this complexity? We’ve only had to use three additional pins for the 12 push-buttons instead of 12. All the push-buttons are pulled up to logic 1s by the pull-up resistors. Pushing a button has no effect if no displays are selected, because the B outputs are also all 1s. When the leftmost display is selected, B0B_0 is low, and pushing any button in the top row will cause the associated C input to go low, and so on. Since the display and push buttons are scanned with the same set of signals, the code that does the scanning can be combined in the timer interrupt handler.

Note that Figure 6-10 is a simplified diagram. In practice, the B pins would need to be open-collector or open-drain (see “Output Variations” on page 58) devices; otherwise, if two buttons in different rows but the same columns were pushed, we’d be connecting a 1 to a 0, which might damage the parts. However, it’s not normally implemented that way, since the aforementioned display driver circuitry handles that for us.

You can find out whether some device is constructed in a manner similar to Figure 6-10 by pushing multiple buttons at the same time and watching the displays. The displays will look strange. Think about why.

Your alarm clock might have a brightness adjustment for the display. How does that work? By varying the duty cycle of the display, illustrated in Figure 6-11.

[!visual-conversion]

Cropped from the scan (PDF page 189, printed p. 149):

Each display is lit one-quarter of the time in the left part of Figure 6-11. The right part shows each display lit only one-eighth of the time; no displays are lit half of the time. The result is that the displays on the right appear approximately half as bright as those on the left. The “brightness” is related to the average time that the display is on. Note that the relationship between duty cycle and perceived brightness is unlikely to be linear.

A common sensor task is to determine the position of a rotating shaft—think motors, wheels, and knobs. We could determine the position by using switches on the shaft or by using black and white spots that could be read with a photosensor. Whatever approach we take, we’d encode each shaft position as a binary number. The encoder might look like Figure 6-12 if we cared about eight different positions. If the white sectors are 0s and the black sectors are 1s, then you can see how we can read the position value. The radial lines are not part of the encoder; they’re just there to make the diagram easier to understand.

[!visual-conversion]

Cropped from the scan (PDF page 189, printed p. 149):

As usual, this seems simple, but it isn’t. In this case, the problem is mechanical tolerances. Note that even with a perfectly aligned encoder, we’d still have issues resulting from propagation delay differences in the circuitry reading each bit. What happens if the encoder isn’t perfectly aligned, as in Figure 6-13?

[!visual-conversion] Binary rotary encoder with 8 sectors labeled 0-7 Cropped from the scan (PDF page 189, printed p. 149): Binary rotary encoder with 8 sectors labeled 0-7

[!visual-conversion] Binary rotary encoder alignment error diagram with numbered segments 0-7 Cropped from the scan (PDF page 190, printed p. 150): Binary rotary encoder alignment error diagram with numbered segments 0-7

Figure 6-13: Binary rotary encoder alignment error

Rather than reading 01234567 as we’d expect, we get 201023645467. American physicist Frank Gray (1887–1969) at Bell Telephone Laboratories took a look at this problem and came up with a different encoding in which only the value of a single bit changes for each position. For the 3-bit encoder we’ve been looking at, the eponymous Gray code is 000, 001, 011, 010, 110, 111, 101, 100. The code can easily be translated to binary using a small table. Figure 6-14 shows a Gray code version of our encoder wheel.

[!visual-conversion] Gray code rotary encoder wheel with numbered segments 0-7 Cropped from the scan (PDF page 190, printed p. 150): Gray code rotary encoder wheel with numbered segments 0-7

Figure 6-14: Gray code rotary encoder

There’s a twist on 2-bit Gray codes we can use when we don’t really need to know the absolute position of something, but need to know when the position changes and in which direction. Some of the knobs on your car dashboard, such as the volume control on the stereo, are likely to work this way. A good indicator is if turning a knob while the ignition is off has no effect once the car is started. The twist is called quadrature encoding because there are four states. The 2-bit Gray code pattern is repeated multiple times. For example, there are cheap quadrature encoders that are good to 1/4,096 of a revolution. Quadrature takes only two sensors, one for each bit. An absolute 4,096-position encoder would take 12 sensors.

The quadrature waveform is shown in Figure 6-15.

Figure 6-15: Quadrature waveform

As you can see, when the shaft is rotated clockwise, it produces the sequence 0132; counterclockwise yields 2310. We can form a 4-bit number out of the current position and the previous position. This number tells us the direction of rotation, as Table 6-1 shows.

Table 6-1: Quadrature Rotation Detection

Current Previous Combined Meaning
00 00 0 Illegal
00 01 1 Clockwise
00 10 2 Counterclockwise
00 11 3 Illegal
01 00 4 Counterclockwise
01 01 5 Illegal
01 10 6 Illegal
01 11 7 Clockwise
10 00 8 Clockwise
10 01 9 Illegal
10 10 a Illegal
10 11 b Counterclockwise
11 00 c Illegal
11 01 d Counterclockwise
11 10 e Clockwise
11 11 f Illegal

Note that this is a state machine, where the combined value is the state. What do you get when you take a pair of quadrature encoders, orient them at 90 degrees from each other, and stick a rubber ball in the middle? A computer mouse.

[!visual-conversion] Quadrature waveform diagram showing X and Y signals with clockwise/counterclockwise … Cropped from the scan (PDF page 191, printed p. 151): Quadrature waveform diagram showing X and Y signals with clockwise/counterclockwise direction and phase sequence 0132.

Parallel communication is an extension of what we saw earlier when lighting up LEDs. We could hook up eight LEDs to port B and flash ASCII character codes. Parallel means we have a wire for each component and can control them all at the same time.

You may have an IEEE 1284 parallel port on your computer if it’s an old model. These were commonly used for printers and scanners before Universal Serial Bus (USB) came along. And yes, there were eight data lines on the parallel port so you could send ASCII character codes.

There’s a problem with all of this, though: how do you know when the data is valid? Let’s say you send the characters ABC. How do you know when it’s the next character? You can’t just look for some change, because it could be AABC. One way is to have another “look at me” signal. IEEE 1284 had a strobe signal for this purpose. In Figure 6-16, the data on bits 0 through 7 is valid whenever the strobe is low or 0.

Figure 6-16: Parallel data strobe timing

Another parallel interface that has pretty much gone by the wayside is IDE. This is what’s used to communicate with older disk drives.

Parallel interfaces are expensive because they require many I/O pins, connector pins, and wires. The parallel port had a 25-pin connector and a big fat cable. IDE had 40 wires. There’s a limit to how fast a signal can be sent down a wire, and when that’s exceeded, multiple wires are needed.

It would be nice to be able to communicate using fewer wires because wires cost money, which adds up, especially when you’re talking about long distances. Two wires is the minimum number required because we need a return signal path for the electricity, as you learned in Chapter 2. We’re not going to show that return path in the diagrams for simplicity.

[!visual-conversion] Timing diagram showing Bit 0-7 and Strobe signals over time … Cropped from the scan (PDF page 192, printed p. 152): Timing diagram showing Bit 0-7 and Strobe signals over time with hex values 0x42, 0x6f, 0x21.

How could we send the eight signals over a single wire? We can get a hint by looking at the timing diagram in Figure 6-16. Even though each bit is on its own wire, the characters are spaced out in time. We can space out the bits in time too.

I talked about shift registers in “Shiftiness” on page 99. On the transmitting end, the strobe or clock signal shifts all the bits over one position and sends the bit that falls off the end out on the wire. On the receiving end, the clock shifts all the bits over by one position and puts the state of the data line into the newly vacated position, as shown in Figure 6-17.

[!visual-conversion] Diagram of serial communications using shift registers with Input, Transmitter … Cropped from the scan (PDF page 193, printed p. 153): Diagram of serial communications using shift registers with Input, Transmitter shift register, Data, Clock, Receiver shift register, and Output.

Figure 6-17: Serial communications using shift registers

We’d use a counter to tell us whenever we get to 8 bits, and then we could do something with the value. This approach takes two wires, not one, and it’s pretty error-prone. It requires that the transmitter and receiver be synchronized, or in sync—which has nothing to do with the boy band. All we’d have to do is miss one clock, and everything would be garbled. We could add a third wire that said when we were starting a new character, but our goal is to minimize the number of wires.

A long time ago (in the early 1900s), the telegraph was married to the typewriter to make the teletype, a machine that allowed typing to a printer far away. Teletype machines were initially used to allow stock market information to be sent over telegraph wires.

The data was sent using a serial protocol (set of rules) that worked using just one wire in addition to the return path. The clever thing about this protocol is that it worked sort of like the timers at a swim meet. Everybody starts their individual timers when the starting gun goes off, and they’re close enough that it works. Figure 6-18 illustrates the protocol.

[!visual-conversion] Mark-space signaling timing diagram showing first and second character bit … Cropped from the scan (PDF page 193, printed p. 153): Mark-space signaling timing diagram showing first and second character bit sequences with Start and Stop markers.

Figure 6-18: Mark-space signaling

The line here is in a 1, or high, state when nothing is happening. The high state is called mark, and the low state is called space, after the way early telegraph equipment either made a mark or left a space on a strip of paper. The line going low in Figure 6-18 is the starting gun, and it’s called the start bit. Following the start bit, the 8 bits of data are sent. The character

ends with a pair of high stop bits. Each bit is allotted the same amount of time. Synchronization errors can occur, but all the transmitter has to do is to be quiet for a character time and the receiver will sync up. We’re dividing up time so that we have a slot for each bit and then multiplexing the data onto the single wire. This technique, called time division multiplexing, can be implemented using a selector (see “Building Selectors” on page 65) instead of a shift register. The speed in bits per second, by the way, is known as the Baud rate, named after French engineer Émile Baudot (1845–1903).

Teletypes were awesome machines. They didn’t contain any electronics and worked by having a motor spin a shaft. An electromagnet released the shaft when a start bit came in so it could spin. At each place in the rotation for the bit position, all sorts of cams and levers and pushrods would move around, ultimately whacking a metal character onto an inked ribbon and then onto a piece of paper. You knew that a message was coming in when stuff started rattling off the shelves. The keyboard worked in a similar fashion. Pressing a key started a shaft spinning that would move an electrical contact, depending on which keys were pressed, to generate an ASCII code.

Another cool trick, called a half-duplex connection, is where a transmitter and a receiver on each end share the same wire. Only one can talk at a time, or gibberish results. That’s why radio operators said things like “over.” You know all about half-duplex communications if you’ve ever used a walkie-talkie. A collision results when more than one transmitter is active at the same time, garbling the data. A full-duplex connection is when there are two wires, one going in each direction.

All of the circuitry to implement this eventually became available in a single integrated circuit called a UART, which stands for Universal Asynchronous Receiver-Transmitter. Software can also implement a UART with an approach called bit-banging.

A standard called RS-232 defined the voltage levels used for mark and space on old serial ports, as well as many additional control signals. It’s pretty much been replaced by USB now, although a variant called RS-485, which uses differential signaling (refer back to Figure 2-32) for greater noise immunity, is used in industrial environments. The parallel IDE interface to disks has been replaced by SATA, the serial equivalent. Electronics are now fast enough that we can do many things serially that we used to have to do in parallel. Also, wires remain expensive. The world is running low on copper extractable from the earth, which is what’s used for the conductor in wires. Recycling existing copper products is now a major source of copper. Chips are mostly silicon, which is found in sand and very abundant.

There are a number of serial interfaces designed for connecting peripherals up to small microcomputers. These include SPI, I2C, TWI, and OneWire.

There’s a big problem with mark-space signaling, which is that it’s not good for very long distances. It doesn’t work over telephone lines for reasons that are beyond the scope of this book. That was a big deal because once the

telegraph was replaced by better technologies, the only remaining long-distance communication technologies were telephone and radio. This mark-space signaling problem is solved with the same trick that makes radio work.

The universe contains all kinds of different waves. There are waves in the ocean, sound waves, light waves, microwaves, and all sorts of stuff in between. The fundamental wave is a sine wave. All other wave shapes can be made from combinations of sine waves. You get a sine wave by plotting the height of a point on a circle versus the angle. It looks like Figure 6-19.

[!visual-conversion]

Cropped from the scan (PDF page 195, printed p. 155):

Figure 6-19: Sine wave

The height of the sine wave is the amplitude. The number of same-direction zero crossings per second is the frequency, measured in Hertz, after German physicist Heinrich Hertz (1857–1894). Hertz is abbreviated Hz and is synonymous with cycles per second. The distance between two same-direction zero crossings is the wavelength. They’re related as follows:

λ=vf\lambda = \frac{v}{f}

In this equation, λ\lambda is the wavelength in meters, ff is the frequency in Hertz, and vv is the speed of the wave in the medium in which it’s traveling. That’s the speed of light for radio waves. The higher the frequency, the shorter the wavelength. Just as a reference point, middle C is about 261 Hz these days.

If you stop to think about it, you’ll realize that different waves have different properties. Sound waves don’t travel very far and are stopped by a vacuum but go around corners. Light waves go a very long way but are stopped by a wall. Some frequencies of radio waves go through walls, but others don’t. There’s a lot of variation in between.

Time to surf. Let’s find a wave that does what we want and hitch a ride. We’ll call this wave the carrier, and what we want to do is modulate or change it based on the signal we care about, such as our mark-space waveform.

AT&T introduced the Bell 103A data set in the early 1960s. It provided full duplex communications at a whopping 300 Baud over a telephone line by using four audio frequencies; each end of the connection got its own pair of mark and space tones. This is called frequency shift keying (FSK) because the frequency shifts with the marks and spaces. You can see it in Figure 6-20.

[!visual-conversion] Frequency shift keying waveform for ASCII letter A, labeled Start, … Cropped from the scan (PDF page 196, printed p. 156): Frequency shift keying waveform for ASCII letter A, labeled Start, 0-7, Stop

Figure 6-20: Frequency shift keying—ASCII letter A

The receiving end has to turn the audio back into marks and spaces, called demodulation, the opposite of modulation. Devices that do this are called modems. The weird noises you hear when someone uses a dial-up connection to the internet or sends a fax in a cheesy movie are the frequencies used by modems.

USB is not all that interesting, but it’s worth a mention because it’s so common. It features more incompatible and hard-to-use connectors than any other standard and is arguably more important for device charging than for data transfer.

USB replaced many of the bulky connectors that were proliferating on computers in the mid-1990s, such as the PS/2, RS-232, and parallel ports with a single four-wire connector. There were two power wires and a twisted pair for data using differential signaling. USB repeats the pattern we’ll see more of soon of “can’t stop there,” so now USB Type-C is up to 24 wires, just shy of the old parallel port.

USB is not a free-for-all. There is a controller that is in charge of all of the endpoints, as opposed to everything having equal footing. The data transfer is structured; it’s not just shoveling uninterpreted bits around. It uses a common technique: data is transferred in packets, which are equivalent to packages sent through the mail. Packets contain a header and optional payload. The header is essentially the information that you’d find on the outside of a package—where it came from, where it’s going, the class of postage, and so on. The payload is the contents of the package.

USB handles audio and video via isochronous transfers. An endpoint can ask to reserve a certain amount of the bandwidth (data transfer rate), yielding a guarantee that data can be transferred. The controller refuses the request if there isn’t enough bandwidth.

It’s difficult to get a clear picture of the modern world of networking without knowing its origins. It drives me crazy when my daughter says, “The Wi-Fi is down” or, “The internet isn’t working,” because they’re not the same thing. Attempts to explain this to her are met with the patented teenage eye roll and hair toss.

Two general classifications are used to describe networks. A local area network (LAN) is a network that covers a small geographic area such as a home or an office. A wide area network (WAN) covers a large geographic area. These terms are somewhat fuzzy since there is no exact definition of small and large.

The original network was the telegraph network, which evolved into the telephone network. It didn’t start as a computer network because computers didn’t exist at the time. The original telephone network was a circuit-switched network. When a call was made between parties, their wires were effectively connected together, forming a circuit. It was switched because that connection existed only for the duration of the conversation. Once a call was completed, new circuits could be created.

With a few exceptions, such as the remaining landlines, the phone system is now a packet-switched network. I mentioned packets in the last section. Communications are divided up into packets that include sender and recipient addresses. Packets can share wires using time division multiplexing (covered earlier in “Serial Communication” on page 152), which allows for more efficient use of circuits; this became possible when the amount of data that could be sent over a wire became more than was needed just for voice.

One of the earliest computer networks was part of Semi-Automatic Ground Environment (SAGE), a Cold War–era defense system. It used modems on the telephone network for communications between sites.

Many organizations started experimenting with LANs in the late 1960s. For example, my lab at Bell was developing graphics terminals that were connected to our department’s Honeywell DDP-516 computer using a LAN called the ring. At the time, peripherals such as tape drives and printers were very expensive, and most departments didn’t have their own. But they were available in the main computer center. Our computer was connected to a modem, and when it needed something it didn’t have, it would just call up the computer center. It was effectively a WAN. Not only could we send things off to be printed, we could also send programs that would be run, and the computer center would call our machine back with the results.

Similar activity was occurring at many research labs and companies. Many different LANs were invented. Each was its own private universe, though—they couldn’t talk to each other. Modems and phone lines were the basis for wide-area communications.

A set of computer programs developed at Bell Labs called UUCP (for UNIX-to-UNIX copy) was released to the outside world in 1979. UUCP allowed computers to call each other to transfer data or run programs remotely. It formed the basis for early email and news systems such as USENET. These systems were an interesting hack. If you wanted to send data across the country, it would hop from machine to machine until it got to its destination. This usually allowed long-distance phone charges to be avoided.

Meanwhile, ARPA, the Advanced Research Projects Agency of the US Department of Defense, was funding the development of the ARPANET, a packet-switched WAN. The ARPANET evolved into the internet in the 1990s. Most people take the internet for granted today, and like my daughter, they probably think it’s synonymous with networking. But its real nature is indicated right there in the name. It’s a contraction of inter and net. The internet is a network of networks—it’s the WAN that connects the LANs together.

A lot of other stuff that we take for granted these days was invented at the Xerox Palo Alto Research Center (PARC) in the mid-1970s. For example, an American electrical engineer by the name of Bob Metcalfe invented Ethernet, which is a LAN because it’s not designed to go very far.

NOTE Check out Adele Goldberg’s book A History of Personal Workstations (Addison-Wesley, 1988) for more about the history of PARC.

The original Ethernet was a half-duplex system. Every computer was connected to the same wire. Each computer network interface had a unique 48-bit address called a Media Access Control (MAC) address, and that’s still the case today. Data is organized into packets, called frames, of about 1,500 bytes. Frames have a header that includes the sender address, the recipient address, and some error checks (for example, cyclic redundancy checks, or CRCs, as discussed in “Error Detection and Correction” on page 88) along with the data payload.

Normally, one computer would talk, and the others would listen. Computers that didn’t match the recipient’s MAC address would ignore the data. Each machine listened to what was going on and didn’t transmit if someone else was transmitting. When machines did start transmitting at the same time, the collision resulted in garbled packets, just like the half-duplex collisions described earlier. One of Metcalfe’s big innovations was random back-off-and-retry. Each machine that was trying to talk would wait a random amount of time and then try to resend.

Ethernet is still in use today, though not the half-duplex version. Now machines are connected to routers that keep track of which machine is at which connection and routes packets to the right places. Collisions no longer happen. Wi-Fi is essentially a version of Ethernet that uses radio instead of wires. Bluetooth is another popular LAN system. Think of it as a version of USB that ditches the wires for radio.

As you now know, the internet is not actually a physical network; it’s a set of layered protocols. It’s designed in such a way that the lower layers specifying the physical network can be replaced without affecting the upper layers. That design allows the internet to function over wires, radio, optical fibers, and whatever new technologies come along.

Transmission Control Protocol/Internet Protocol (TCP/IP) is the pair of protocols on which the internet is built. IP gets packets from place to place. These packets, called datagrams, are like telegrams for computers. As with real telegrams, the sender doesn’t know when or even whether the recipient got the message. TCP is built on top of IP and makes sure that packets get reliably delivered. This is a pretty complicated job, because large messages

span many packets that may not arrive in order since they may have taken different routes—not much different from ordering some stuff and having it shipped in multiple boxes that may not all arrive on the same day or even be sent via the same carrier.

Each computer on the internet has a unique address known as its IP address. Unlike MAC addresses, IP addresses aren’t tied to the hardware and can change. The IP address system is a hierarchical system in which someone gives out blocks of addresses, who in turn give out blocks of addresses, and so on until it gets down to whoever gives your machine its address.

The internet pretty much runs on IPv4, version 4 of IP, which uses 32 bits of address. Addresses are written in octet notation of xxx.xxx.xxx.xxx, where each xxx is 8 of the 32 bits written in decimal. That’s over 4 billion addresses, yet that’s not enough. Now that everyone has an address for their desktop, their laptop, their tablet, their cell phone, and their other gadgets, there are no more addresses to give out. Hence, the world has been slowly migrating to IPv6, which has 128-bit addresses.

How can you be found if your address can change? That’s handled by the Domain Name System (DNS), which is like a phone book, for those who remember what those are. DNS maps names to addresses. It knows that whitehouse.gov has the IP address 23.1.225.229 at the time that I’m writing this. It’s sort of like the address book in your phone, except you have to keep that up-to-date; DNS takes care of everything whenever anybody moves.

Many other protocols are built on top of TCP/IP, such as the Simple Mail Transfer Protocol (SMTP) that makes email work. One of the most used protocols is HTTP, short for HyperText Transfer Protocol, which is used for web pages, along with HTTPS where the S stands for secure.

Hypertext is just text with links. American engineer Vannevar Bush (1890–1974) came up with the idea in 1945. It didn’t really take off until Tim Berners-Lee, a scientist at CERN (the European Organization for Nuclear Research), invented the World Wide Web so that physicists could share information.

The HTTP standard defines how web browsers interact with web servers. Web browsers are what you use to view web pages. Web servers send you those pages upon request. Web pages are found and fetched by a Uniform Resource Locator (URL), the website address in the address bar of your browser. It’s how you locate the information you want and includes the domain name of a machine on the internet and a description of where to find the information on that machine.

Web pages typically start their lives as HTML (short for HyperText Markup Language), the most common language in which web pages are written. HTML has gotten a lot of stuff stuck onto it over time and is now a pretty complicated mess. More on this in Chapter 9.

Computers are in lots of entertainment devices, from audio players to televisions. You may have noticed that digital photos don’t look very good when they’re magnified beyond a certain point. Our real-world experience of sound and light is continuous, but computers have no way to store continuous things. The data must be sampled, which means we have to take readings at points in time and/or space. An analog (continuous) signal must then be reconstructed from those samples for playback.

NOTE
There’s a good video called “Episode 1: A Digital Media Primer for Geeks” that you can find online that is a good introduction to sampling. There’s a second episode, which is also good, but it’s very misleading. While everything said is technically correct, it only applies to mono, not stereo. The presenter implies that it’s good for stereo, but it isn’t.

Sampling isn’t a new thing; even back in the days of silent movies, the scene was sampled at about 16 frames per second. There’s an entire field called discrete mathematics that deals with sampling. Discreetly, of course.

We talked about the differences between analog and digital way back in Chapter 2. This book is about digital computers, and many real-world applications require computers to generate analog signals, interpret analog signals, or both. The following sections discuss how computers accomplish this.

How might we generate an analog voltage based on a digital number? The blithe and correct answer is: by using a digital-to-analog converter. How would we construct one of these?

Let’s go back to Figure 6-1, where we have an LED connected to an I/O port. In Figure 6-21, we hook an LED to each of the eight pins of port B.

Figure 6-21: Digital-to-analog converter using LEDs

[!visual-conversion] Digital-to-analog converter using LEDs with pins PB0 to PB7 Cropped from the scan (PDF page 200, printed p. 160): Digital-to-analog converter using LEDs with pins PB0 to PB7

Now we can generate nine different light levels—from no LEDs on to eight LEDs on. But nine levels from 8 bits isn’t a very good use of bits; with 8 bits, we should be able to get 256 different levels. How? Just like we do with numbers. Figure 6-22 hooks one LED to bit 0, two to bit 1, four to bit 2, and so on.

[!visual-conversion] Schematic of a digital-to-analog converter using LEDs with PB0 to … Cropped from the scan (PDF page 201, printed p. 161): Schematic of a digital-to-analog converter using LEDs with PB0 to PB7 inputs and LED group totals.

Figure 6-22: Better digital-to-analog converter using LEDs

That’s a whole lotta LEDs. You could hang this circuit from a balloon to make a LED zeppelin. Moving on, you can see that this mirrors our binary representation of numbers. Bit 1 produces twice as much light as bit 0, bit 2 four times as much, and so on.

We used the LED example to illuminate the workings of a digital-to-analog converter. A real digital-to-analog converter (D/A or DAC) produces a voltage instead of light. The term resolution is loosely used to describe the number of “steps” a DAC can produce. I say “loosely” because it’s common to say that a DAC has, for example, 10 bits of resolution, which really means that it has a resolution of 1 part in 2102^{10}. To be completely correct, the resolution is the maximum voltage that the DAC can produce divided by the number of steps. For example, if a 10-bit DAC could produce 5V maximum, then it has a resolution of approximately 0.005V.

Figure 6-23 shows the symbol used for a DAC.

[!visual-conversion] DAC schematic symbol with inputs D0-n and output Vout Cropped from the scan (PDF page 201, printed p. 161): DAC schematic symbol with inputs D0-n and output Vout

Figure 6-23: DAC schematic symbol

We can generate analog waveforms using a DAC. This is how audio players and music synthesizers work. All we need to do is to change the DAC inputs at a regular rate. For example, if we had an 8-bit DAC connected to port B, we could generate the sawtooth wave shown in Figure 6-24.

int i = 0;
while (true)
PORTB = i++;

Figure 6-24: Synthesized sawtooth wave

For more complex waveforms, devices usually incorporate memory that can be written with the data, which is then read out by additional circuitry. This ensures a constant data rate that is independent of whatever else the CPU is doing. A typical way of implementing this is by creating a FIFO (“first in, first out”) configuration, as shown in Figure 6-25. Note that a FIFO is the same thing as a software queue.

Data bus In → [Memory] → Out → DAC → Analog out
↑ ↑
High-water mark Low-water mark

Figure 6-25: FIFO with high- and low-water marks

Two triggers are associated with the FIFO memory: a high-water mark and a low-water mark, which borrow their terminology from tides. The low-water mark triggers an interrupt when the FIFO is close to empty; the high-water mark triggers when it’s close to full. This way, higher-level software can keep the memory filled so that the output is continuous. Though it’s not exactly a FIFO because newly added water mixes with the old, this is how water towers work; when the water is below the low-water mark, the pump turns on to fill the tank; when the high-water mark is reached, the pump turns off. FIFOs are really handy for connecting things that operate at different speeds.

Analog-to-digital conversion, the opposite process, is done using an A/D, or ADC, which is more complicated than a DAC. The first problem that arises is getting the analog signal to hold still, because we can’t measure it if it’s wiggling around. (You know the problem if you’ve ever tried to take a little kid’s temperature.) In Figure 6-26, we need to take a sample of the input waveform—more than one if we want our digitized version to resemble the analog original. We do this using a circuit called a sample and hold, which is the analog equivalent of a digital latch (see “Latches” on page 71).

[!visual-conversion] Synthesized sawtooth wave with C code snippet Cropped from the scan (PDF page 202, printed p. 162): Synthesized sawtooth wave with C code snippet

[!visual-conversion] FIFO memory diagram with data bus, high-water mark, low-water mark, … Cropped from the scan (PDF page 202, printed p. 162): FIFO memory diagram with data bus, high-water mark, low-water mark, and DAC output

[!visual-conversion] Sample and hold circuit diagram with Analog in, Sample switch, … Cropped from the scan (PDF page 203, printed p. 163): Sample and hold circuit diagram with Analog in, Sample switch, Holding tank, and Analog sample output.

When we take a sample by closing the switch, the current value of the analog signal is stored in the holding tank. Now that we have a stable signal in the holding tank, we need to measure it so we can generate a digital value. We need something that compares the signal to a threshold similar to what we saw in the right half of Figure 2-7, back in Chapter 2. Fortunately, an analog circuit called a comparator can tell us when one voltage is greater than another. It’s just like a logic gate except that we can choose the threshold.

The schematic symbol for a comparator is shown in Figure 6-27.

[!visual-conversion] Analog comparator schematic symbol with +, - inputs and Out … Cropped from the scan (PDF page 203, printed p. 163): Analog comparator schematic symbol with +, - inputs and Out output

The output is 1 if the signal on the + input is greater than or equal to the signal on the – input.

We can use a stack of comparators with different reference voltages on the – inputs to build a flash converter, as shown in Figure 6-28.

[!visual-conversion] Flash converter circuit with 8 comparators and reference voltages from … Cropped from the scan (PDF page 203, printed p. 163): Flash converter circuit with 8 comparators and reference voltages from 0.125V to 1.000V

It’s called a flash converter because it generates results quickly, in a flash. As you can see, the outputs are 00000000 for a voltage less than 0.125V, 00000001 for a voltage between 0.125V and 0.250V, 00000011 for a voltage

between 0.250V and 0.375V, and so on. This works, but it has the same problem as our DAC in Figure 6-25: it doesn’t use the bits very efficiently. Flash converters are also relatively expensive parts due to the number of comparators, but they’re the way to go when extreme speed is required. How might we construct a cheaper ADC that better utilizes the bits?

Our flash converter used a set of fixed reference voltages, one for each comparator. We could use a single comparator if we had an adjustable reference voltage. Where might we get one of those? With a DAC!

In Figure 6-29, you can see that we’re using a comparator to test the sampled value in the holding tank against the value of the DAC. Once cleared, the counter counts up until the DAC value hits the sampled value, at which time the counter is disabled and we’re done. The counter contains the digitized value of the sample.

[!visual-conversion] Analog-to-digital converter block diagram with analog input, holding tank, comparator, … Cropped from the scan (PDF page 204, printed p. 164): Analog-to-digital converter block diagram with analog input, holding tank, comparator, and counter.

Figure 6-29: Analog-to-digital converter

Once cleared, the counter counts up until the DAC value hits the sampled value, at which time the counter is disabled and we’re done. The counter contains the digitized value of the sample.

You can see how this works in Figure 6-30. The analog signal wiggles around, but the output of the holding tank is stable once a sample is taken. The counter is then cleared, and it counts up until the DAC output hits the sampled value, at which time the counter stops and we’re done.

[!visual-conversion]

Cropped from the scan (PDF page 204, printed p. 164):

Figure 6-30: ADC in operation

This ADC is called a ramp converter because of the way in which the DAC output generates a ramp. One of the problems with a ramp converter is that it can take a long time since the conversion time is a linear function of the sampled signal value. If the sampled signal is at its maximum value and we have an nn -bit ADC, conversion can take 2n2^n clocks.

One way around this is to use a successive approximation converter, which performs a binary search in hardware, as you can see in Figure 6-31.

[!visual-conversion] Diagram of successive approximation ADC operation showing analog input, take … Cropped from the scan (PDF page 205, printed p. 165): Diagram of successive approximation ADC operation showing analog input, take sample, clear counter, and done steps.

Figure 6-31: Successive approximation ADC in operation

The first clock sets the DAC to one-half of the full range. Since that’s less than the sampled signal, it’s adjusted upward by one-quarter of the full range. That’s too much, so next it’s adjusted downward by one-eighth of the full range. That’s too low, so it’s adjusted up by one-sixteenth of the full range, and we’re there. Worst case, it takes log⁡2n\log_2 n clocks. That’s quite an improvement.

The term resolution is used for ADCs in a manner similar to how it’s used for DACs. The schematic symbol is shown in Figure 6-32.

[!visual-conversion] ADC schematic symbol with input Vin and output D0-n Cropped from the scan (PDF page 205, printed p. 165): ADC schematic symbol with input Vin and output D0-n

Figure 6-32: ADC schematic symbol

Audio involves sampling in one dimension—that is, measuring the amplitude or height of the signal at points in time. Look at the sine wave in Figure 6-33. We have a square wave with some sampling frequency, and we record the height of the signal on each rising edge using an A/D.

[!visual-conversion]

Cropped from the scan (PDF page 205, printed p. 165):

Figure 6-33: Sampling a sine wave

Now that we have a set of samples, we should be able to reconstruct the original signal by feeding them to a D/A. Let’s give it a try, as shown in Figure 6-34.

[!visual-conversion]

Cropped from the scan (PDF page 206, printed p. 166):

Wow, that looks terribly distorted. Looks like we’d need a lot more samples to improve the result so that it looked more like Figure 6-35.

[!visual-conversion]

Cropped from the scan (PDF page 206, printed p. 166):

But we don’t need to. The sampling and reconstruction in Figures 6-33 and 6-34 is actually okay. I’m about to tell you why, but be warned: there’s some heavy theory ahead.

A sine wave is relatively easy to describe, as mentioned in “Catch a Wave” on page 154. But we need a way to describe more complicated waveforms, such as the one in Figure 6-31.

The graphs so far plot amplitude against time, but we can look at it in other ways. Take a look at the musical score in Figure 6-36.

[!visual-conversion] Musical score with treble clef, 4/4 time, and four chords … Cropped from the scan (PDF page 206, printed p. 166): Musical score with treble clef, 4/4 time, and four chords on a staff.

You can see that the score plots musical notes against time, but there’s more happening. We don’t just have notes at each point in time; we have chords, which are constructed from multiple notes. Let’s look at the first chord, which contains the notes G₄ (400 Hz), B₄ (494 Hz), and D₅ (587 Hz). Pretend we’re playing the chord on a synthesizer that can generate sine waves for the notes. You can see in Figure 6-37 that although each note is a sine wave, the chord itself is a more complex waveform, being the sum of the three notes. It turns out that any waveform can be represented as the weighted (multiplied by some scale factor) sum of a set of sine waves. For example, if the square wave in Figure 6-33 has a frequency of ff , it can be represented as the sum of sine waves:

sin⁡(f)1+sin⁡(3f)3+sin⁡(5f)5+sin⁡(7f)7+…\frac{\sin(f)}{1} + \frac{\sin(3f)}{3} + \frac{\sin(5f)}{5} + \frac{\sin(7f)}{7} + \ldots

[!visual-conversion] Waveform diagram showing D5, B4, G4 sine waves and their … Cropped from the scan (PDF page 207, printed p. 167): Waveform diagram showing D5, B4, G4 sine waves and their sum as G major chord.

If you have a good ear, you can listen to a chord like this and pick out the component notes. Tone-deaf people have to rely on some mathematical acrobatics called the Fourier transform, invented by French mathematician and physicist Jean-Baptiste Joseph Fourier (1768–1830), who also discovered the greenhouse effect. All the graphs we’ve seen in this section so far plot amplitude against time. The Fourier transform allows us to plot amplitude against frequency. It’s a different way of looking at things. The Fourier transform of our G major chord would look like Figure 6-38.

[!visual-conversion]

Cropped from the scan (PDF page 207, printed p. 167):

You’ve probably seen this sort of thing before without knowing it. Many media players have spectrum analyzer eye candy that displays the volume in different frequency bands using the Fourier transform. Spectrum analyzers originated as complicated pieces of electronic equipment. Now they can be implemented on computers using the Fast Fourier Transform (FFT) algorithm. One of the coolest applications of Fourier analysis is the Hammond B-3 organ.


THE HAMMOND B-3 ORGAN

The Hammond B-3 is an amazing application of electromagnetics and Fourier analysis. The way it works is that a motor drives a shaft on which 91 “tone wheels” are mounted. Each tone wheel has an associated pickup, similar to what’s used on electric guitars, that generates a specific frequency as determined by the bumps on the tone wheels. Since all of the tone wheels are mounted on the same shaft, they can’t get out of tune with each other.

Pressing a key on a B-3 doesn’t just generate the frequency produced by a tone wheel. There are nine eight-position “drawbars” that are used to mix the signal produced by the “fundamental” tone (the note being played) with signals from other tone wheels. The drawbars set the level of the sub-octave, fifth, fundamental, 8th, 12th, 15th, 17th, 19th, and 22nd harmonics.

The sound produced is the weighted sum of these nine signals as set by the drawbars in a manner similar to how we produced our G major chord in Figure 6-37.


Another feature of many media players is the graphic equalizer, which lets you adjust the sound to your taste. A graphic equalizer is a set of adjustable filters, devices that include or exclude certain frequencies. They’re akin to the transfer functions that we saw in “Digital in an Analog World” on page 38, but for frequency instead of voltage or light. There are two main types of filters: low pass, which pass everything below a certain frequency, and high pass, which pass everything above a certain frequency. They can be combined to make bandpass filters that include everything between a low and high frequency, or notch filters that exclude a particular frequency. You can see in Figure 6-39 that the filter edges are not sharp; they roll off. Perfect filters don’t exist. Note that the button debouncer in Figure 6-7 is a low-pass filter.

[!visual-conversion] Four filter response curves: Low pass, High pass, Bandpass, Notch, … Cropped from the scan (PDF page 208, printed p. 168): Four filter response curves: Low pass, High pass, Bandpass, Notch, each plotting Gain vs Frequency.

Figure 6-39: Filters


We could, for example, apply a low-pass filter to our G major chord, as seen in Figure 6-40. Applying a filter effectively multiplies the curves; the filter adjusts the sound level at different frequencies.

[!visual-conversion]

Cropped from the scan (PDF page 209, printed p. 169):

As you can imagine, it no longer sounds the same. The B4 is slightly quieter, and the D5 is all but gone.

Why does all this matter? Figure 6-41 shows the Fourier transform of our reconstructed sine wave from Figure 6-34. I didn’t completely specify everything in that figure, so let’s assume that it’s a 400 Hz sine wave sampled at 3 kHz.

[!visual-conversion]

Cropped from the scan (PDF page 209, printed p. 169):

Note that the x-axis goes on to infinity with frequencies at every multiple of the sampling frequency, plus or minus the frequency of the sampled signal.

What happens if we take that reconstructed sine wave and apply a low-pass filter, as shown in Figure 6-42?

[!visual-conversion]

Cropped from the scan (PDF page 209, printed p. 169):

All the distortion disappears; what’s left is our 400 Hz sine wave. It appears that sampling works, as long as we have appropriate filtering. How do we choose a sample rate and filter?

Harry Nyquist (1889–1976), a Swedish electronic engineer, came up with a theorem that says you have to sample at a rate at least twice the highest frequency if you want to be able to faithfully capture the signal. It’s a nice

theory, but because electronics doesn’t follow ideal mathematics, it helps to sample faster than that in order to have the result sound good. The human hearing range is something like 20 to 20,000 Hz.

Based on all that, we should be able to capture anything that we can hear with a 40 kHz sampling rate. What if we accidentally get a 21 kHz sound, which is undersampled according to Nyquist’s theorem? In that case, we get folding or aliasing. Imagine that the sampling frequency is a mirror and any information greater than that frequency is reflected. Looking back at Figure 6-41, you can see that there are artifacts at the sampling frequency plus or minus the sampled frequency. Because the sampling frequency is much greater than the sampled frequency, these artifacts are far away. A 21 kHz input sampled at 40 kHz would produce an artifact at 19 kHz (40–21). This false signal is called an alias. We don’t get out what we put in. A low-pass filter must be applied before sampling to avoid aliasing.

Compact discs take 16-bit samples at 44,100 Hz—times 2, of course, because it’s stereo. That produces a little more than 175KB/second. That’s a lot of data. Some standard audio-sampling rates are 44.1 kHz, 48 kHz, 96 kHz, and 192 kHz. Why would we bother to sample at the higher rates, since doing so would generate a lot more data and Nyquist says it’s not necessary?

Although the frequency and amplitude of a signal sampled near the Nyquist rate can be reconstructed, the phase cannot. Another new term! Think of the phase as a small shifting in time. You can see in Figure 6-43 that the fatter signal lags (as opposed to leads) the skinnier signal by 45 degrees, making it slightly later in time.

[!visual-conversion]

Cropped from the scan (PDF page 210, printed p. 170):

Figure 6-43: Phase difference in signals

Why does this matter? Well, it doesn’t except for stereo. The phase difference causes a time delay between a signal hitting your left and right ears that tells you where it is in space, as illustrated in Figure 6-44.

[!visual-conversion] Three head diagrams labeled Left, Center, Right, each with a … Cropped from the scan (PDF page 210, printed p. 170): Three head diagrams labeled Left, Center, Right, each with a sound cone pointing to the ear.

Figure 6-44: Phase difference in real life

You do a better job with high frequencies because they have shorter wavelengths relative to the thickness of your head. If your head were so narrow that your ears were in the same place, then there would be no time delay. Fat-headed people get better stereo! That’s one of the reasons why you can get away with a single subwoofer: you can’t really tell where the sound is coming from because the wavelength is so long compared to the thickness of your head that the phase difference is undetectable.

When you’re listening to stereo sound, the phase difference between sounds coming out of the speakers creates the image, the ability to “see” where the musicians are in space. The image is “muddy” without accurate phase. Thus, the rationale for higher sampling rates is better reproduction of phase and stereo imaging. You may never notice this if your listening experience involves cheap earbuds on a cell phone.


FM stereo is an interesting application of sampling and filtering. It’s also a great example of how new functionality was wedged into a system that was never designed for it in a backward-compatible way, meaning that the old system still worked fine.

Back in Figure 6-20, you saw how bits could be used to modulate a frequency. FM stands for frequency modulation. FM radio works by modulating a carrier frequency by an analog signal instead of a digital one.

Carrier frequencies for FM radio stations are allocated every 100 kHz. You saw in Figure 6-41 that sampling generates additional frequencies up to infinity; the same thing happens with modulation. As a result, a low-pass filter has to be applied to the modulated signal or there will be interference with other stations. You saw filter rolloff in Figure 6-39. The steeper the rolloff, the more the filter perturbs the phase, which has a negative effect on the sound. This is shown in part of the radio spectrum in Figure 6-45.

[!visual-conversion] Radio spectrum diagram showing frequency bands 98.3, 98.4, 98.5 with … Cropped from the scan (PDF page 211, printed p. 171): Radio spectrum diagram showing frequency bands 98.3, 98.4, 98.5 with shaded blocks and sloped lines.

Figure 6-45: Radio spectrum

Before stereo, the audio information in a monaural FM signal occupied approximately 15 kHz above the carrier frequency. A receiver removed the carrier, resulting in the original audio. This characteristic had to be preserved in the move to stereo; otherwise, all existing receivers would have stopped working.

(continued)


Figure 6-46 gives an overview of how FM stereo works. A 38 kHz square wave is used to take alternate samples of the left and right channels. A 19 kHz pilot tone is generated that’s synchronized with the sampling square wave. The pilot tone is mixed at a low level that’s hard to hear over music and combined with the samples to make a composite signal that’s broadcast.

[!visual-conversion] Diagram showing FM stereo signal generation with 38 kHz sampling, … Cropped from the scan (PDF page 212, printed p. 172): Diagram showing FM stereo signal generation with 38 kHz sampling, 19 kHz pilot, and composite output.

Figure 6-46: FM signal generation

The clever part is that if we look at the Fourier analysis result in Figure 6-47, the first set of frequencies on the left is the sum of the left and right channels—just what we want for mono. Not a problem for old receivers. The next set of frequencies is the difference between the left and right channels, which would not be picked up on an old mono receiver. However, a stereo receiver can use some simple arithmetic to separate out the left and right channels producing stereo.

[!visual-conversion]

Cropped from the scan (PDF page 212, printed p. 172):

Figure 6-47: FM stereo spectrum

I mentioned earlier that audio involves a lot of data. It would be nice to be able to compress that data so that it takes up less space. There are two classes of compression: lossless and lossy. Lossless compression preserves all the original data. As a result, it can compress things only to about half of their original size. The most popular lossless compression today is FLAC, short for Free Lossless Audio Codec. A codec is a coder-decoder, which is sort of like a modem that knows how to translate things from one coding system to another.

MP3, AAC, Ogg, and their ilk are lossy compression codecs. Some fidelity is lost. They work on psychoacoustic principles. People who have studied the workings of the ear and brain have decided that there are certain things that

you can’t hear, like something quiet that happens right after a loud drum beat. These codecs work by removing these sounds, and that gives them a much better compression ratio than FLAC. But not everybody’s ears are the same. I think MP3s sound horrible.

Visual images are more complicated than audio because we need to sample a two-dimensional space. Digital images are represented as rectangular arrays of picture elements, or pixels. Each pixel in a color image is a triad of red, green, and blue lights. Common displays available today have 8 bits each of red, green, and blue. We saw a commonly used representation back in Figure 1-20.

Computer displays use the additive color system, which can produce almost any color by combining (or adding, hence the name) different amounts of the red, green, and blue primaries. This differs from the subtractive color system used for printing, which makes colors by mixing different amounts of the cyan, magenta, and yellow primaries.

Sampling an image is akin to placing a window screen over the image and recording the color in each square. It’s somewhat more complicated because of point sampling, which means we don’t record the entire square, just a point in the center of each one. Figure 6-48 shows an image sampled using three screens of different resolutions.

[!visual-conversion] Three rows showing image sampling at different resolutions: smooth oval, … Cropped from the scan (PDF page 213, printed p. 173): Three rows showing image sampling at different resolutions: smooth oval, low-res blocky, and high-res pixelated.

Figure 6-48: Sampling an image at different resolutions

You can see that the sampled image looks better with finer, higher-resolution screens, but of course that greatly increases the amount of data. Even with a high-resolution screen, however, we still get jaggy edges. This is due to undersampling and aliasing as per Nyquist, although the math for it is too advanced for this book. As with audio, maybe filtering helps. One way we can filter is by supersampling, or taking multiple samples per square and averaging them together, as shown in Figure 6-49.

[!visual-conversion] Diagram showing supersampling: a pixelated circle on a grid transforms … Cropped from the scan (PDF page 214, printed p. 174): Diagram showing supersampling: a pixelated circle on a grid transforms into a smoother, averaged version.

This doesn’t look great all blown up, but if you hold it far away from your face, you’ll see that it doesn’t look too bad. If you think about it, supersampling is equivalent to upping the sampling rate, as we saw for audio in Figure 6-35.

Images are getting bigger and bigger and take up a lot of space. It’s not clear if enough storage will ever exist for the world’s cat photos and videos. As with audio, we’d like images to take less space so we can fit more of them in the same amount of memory and so they’re faster to transmit over a network. This is addressed, once again, by compression.

The most common image compression right now is JPEG, a standard by the Joint Photographic Experts Group. It involves a lot of mathematical heavy lifting that I’m not going to cover here. A rough approximation of how JPEG works is that it looks for adjacent pixels that are pretty close to the same color and stores a description of that area instead of the individual pixels that it contains. You may have a camera that includes an image quality setting; this setting adjusts the definition of “pretty close.” It’s a color version of our example from “Stacks” on page 122.

JPEG uses knowledge about human perception in a manner similar to lossy audio codecs. For example, it takes advantage of the fact that our brains are more sensitive to changes in brightness than to changes in color.

Yet another step up in multidimensional space, video is a sequence of two-dimensional images sampled at regular time intervals. The time interval is a function of the human visual system. Old movies got by with 24 frames per second (fps); the average person today is pretty happy with 48 fps.

Sampling video isn’t much different than sampling images, except that different artifacts are visually annoying and therefore need to be minimized. The problem is that the sampling artifacts along edges, which we saw in Figure 6-48, don’t stay still when objects are moving.

To understand this better, take a look at Figure 6-50, which shows a diagonal line that is moving from left to right over time. It’s only moving a fraction of a pixel per frame, which means it doesn’t get sampled the same every time. It still looks like an approximation of a line, but each one is a different approximation. This makes edges “swim,” which is visually disturbing. Filtering using supersampling is one way to reduce such unpleasant visual artifacts.

[!visual-conversion] Diagram showing diagonal line movement across grid frames 0-3, resulting … Cropped from the scan (PDF page 215, printed p. 175): Diagram showing diagonal line movement across grid frames 0-3, resulting in pixelated black shapes below, labeled ‘Time’.

Video produces a lot more data than images or audio. UHD video has a resolution of 3,840×2,160 pixels. Multiply that by 3 bytes per pixel and 60 frames per second, and you end up with a whopping 1,492,992,000 bytes per second! Obviously compression is very important.

The observation that only part of the image normally changes from frame to frame is the key to video compression. Look at Figure 6-51, in which Mr. Sigma is on his way to pick up a package.

[!visual-conversion] Three panels showing a stick figure approaching a door labeled … Cropped from the scan (PDF page 215, printed p. 175): Three panels showing a stick figure approaching a door labeled ‘Ring Bell for Service’ under a ‘Gaussian Distribution Company’ roof, with ‘Area of change’ marked in the third panel.

As you can see, very little of the image changes between frames. Much less data needs to be stored or transmitted if we only need the data from the area of change. This technique is called motion compression.

One of the problems with representing video as a set of changes from an original image is that sometimes data can get garbled. You’ve probably seen some blocky artifacts on digital TV or when playing a damaged video disc.

We need some way to recover the data. This is done by regularly including keyframes in the data. A keyframe is a complete image, so even if damage accumulates due to corrupted change data, recovery takes place when the next keyframe is encountered.

The algorithms to detect differences between frames are complicated and very compute intensive. Newer compression standards such as MPEG4 include support for layering, which takes advantage of the fact that a lot of video is now computer generated. Layering works just like the old hand-drawn cel animation that we discussed in Chapter 1, where objects painted on transparencies were moved over a stationary background image.

Computers are a lot like teenagers with cell phones. They spend most of their time messaging each other but occasionally have time to talk to people. This section covers some of how computers interact with people.

Not that long ago, the keyboard, mouse, and display or touchscreen you’re so used to were unimaginable luxuries.

There was a time when the way you interacted with a computer was to write a program or data down on paper using special coding forms. You’d hand those to someone who would use a keypunch to turn the forms into a stack of punched cards (refer back Figure 3-25). You’d take those cards, being careful not to drop them, and give them to a computer operator who would put them into a card reader, which would read them into the computer and run the program. This approach, known as batch processing, was used because computers were really slow and expensive, making computer time really valuable, so while your cards were being punched, somebody else’s program was being run.

Computers got faster, smaller, and cheaper. By the late 1960s, it was possible to have a small computer for your company or department. Small as an RV. Computer time became a bit less scarce. The obvious thing happened, which is that people started hooking them up to teletypes. Teletypes were called terminals because they were at the end of the line. A particularly popular model, the Teletype ASR-33, had a keyboard, printer, paper tape (Figure 3-26) punch, and a paper tape reader. The paper tape was the

equivalent of a USB memory stick. An ASR-33 was good for a jaw-dropping 10 characters per second! The term TTY is still with us today as an abbreviation for teletype.

Time-sharing systems were invented to keep these smaller computers busy. Yes, they really were like time-share vacation rentals. You can pretend that it’s your place, and it is your place while you’re there, but other people use it when it’s not your turn.

A time-sharing system has an operating system program that runs on the computer. The OS program is like the booking agent for a time-share rental. Its job is to allocate the various resources of the computer to each user. When it was your turn to use the machine, the other user’s programs would get swapped out to disk, and yours would be loaded into memory and would run for a while. This all happened fast enough that you’d think that you had the machine to yourself, at least until things got busy. At some point, things would start to thrash, as the operating system spent more time swapping things in and out than it did running users’ programs.

Thrashing made time-sharing systems pretty slow when there were a lot of users. Programmers started working late at night because they could have the machines to themselves after everybody else went home.

Time-sharing systems are multitasking in that the computer is presenting the illusion that it’s doing more than one thing at a time. All of a sudden, lots of terminals were connected to the same machine. And the concept of a user appeared so that machines could tell what belonged to who.

Time marched on, and better versions of teletype-like things appeared, and each generation was faster and quieter. But they were still printing things on paper, or hard copy. And they were pretty much only good for text. The Teletype model 37 added Greek characters so that scientists could print math. IBM Selectric terminals had interchangeable typeballs that allowed the user to change fonts. This included a font with dots in different positions that enabled graph drawing.

There were a lot of reasons to move away from hard-copy terminals, including speed, reliability, and noise. Screens existed for things like radar and television; it was time to make them work with computers. This happened slowly due to the evolution of electronics. Memory was just too expensive and slow.

Graphics terminals were originally built around a variation of the vacuum tube (see “Vacuum Tubes” on page 50) called a cathode ray tube (CRT). The inside of the glass is coated with a chemical phosphor, which glows when it’s hit by electrons. By having more than one grid or deflection plate, it’s possible to draw pictures on the phosphor. It’s like having a really talented batter who can hit any target with a ball.

There are actually two ways to make this display work. The deflection plate version, called electrostatic deflection, uses the same principle that gives

you the dreaded static cling. The other option is the electromagnet version, called electromagnetic deflection. In either case, bits need to be translated into voltages, which is yet another application for our D/A building block.

Today the CRT is mostly a relic that has been replaced by the liquid crystal display (LCD). Liquid crystals are substances that can change their light transmission properties when electricity is applied. A typical flat-screen display is much like a CRT in that there are three blobs of liquid crystal at every raster point with red, green, and blue filters and a light that shines through from the back. We still talk to LCD devices as if they’re CRTs, but that’s just a historical artifact. LCDs are now ubiquitous and have replaced CRTs in most applications; LCDs have made cell phones, laptops, and flat-screen TVs possible.

Early screen-based terminals were called glass ttys because they could display only text. These terminals displayed 24 rows of 80 characters each, for a total of 1,920 characters. Since a character fit into a byte, that was less than 2 KiB of memory, which was affordable at the time. Over time, more features got added, such as on-screen editing and cursor motion, which were eventually standardized as part of ANSI X3.64.

A CRT works pretty much like a piece of graph paper. An electron beam moves to some point based on the x- and y-axis voltages. There’s also a z-axis that determines the brightness. Originally there was no color, so these were black-and-white, or grayscale, displays. The number of coordinate locations per inch is called the resolution.

Vector graphics is all about drawing lines, or vectors. You make a picture by drawing a set of lines from here to there. The skinny arrows in Figure 6-52 are drawn with the brightness all the way down or off.

[!visual-conversion] Vector graphics diagram showing a house shape with numbered arrows … Cropped from the scan (PDF page 218, printed p. 178): Vector graphics diagram showing a house shape with numbered arrows indicating vector paths.

Figure 6-52: House of vector graphics

The white arrow with the black outline is drawn twice, once with the brightness on and then again with the brightness off. Drawing the same line twice with the brightness on makes it twice as bright, which we don’t want to do just because we’re changing position.

The house in Figure 6-52 is drawn from a display list, which is a list of drawing instructions. It looks like Figure 6-53.

  1. Move to (2, 0)
  2. Draw to (2, 5)
  3. Draw to (7, 5)
  4. Draw to (7, 0)
  5. Draw to (2, 0)
  6. Move to (2, 5)
  7. Draw to (8, 7)
  8. Draw to (7, 5)
  9. Move to (6, 0)
  10. Draw to (5, 3)
  11. Draw to (4, 3)
  12. Draw to (4, 0)
  13. Restart at step 1

Figure 6-53: Display list

Note the last instruction. We start over again because the image on the screen fades pretty quickly. This works only because of the persistence of the CRT phosphor, which is how long it stays lit once the beam moves away, and the slow response of the human eye. We have to keep doing this over and over to keep the image displayed on the screen.

There’s more to this instruction, however. There’s a lot of 60 Hz radiation around us because that’s the frequency of American alternating current electric power (it’s 50 Hz in some other countries). Despite our best attempts at shielding, this radiation affects our display and makes it wiggle. Thus, graphics terminals like the GLANCE G developed at Bell Telephone Laboratories had a “restart at step 1 after the next time the power line crosses 0 from the positive to the negative” instruction. This synchronized the drawing to the interference so that it always wiggled exactly the same and therefore wasn’t noticeable.

Drawing the image took time, a nasty side effect of which was that everything looked fine until the display list got long enough that it couldn’t be drawn in one-sixtieth of a second. It suddenly got very flickery when it drew only once every one-thirtieth of a second.

A company called Tektronix had an interesting solution to the flicker problem, called the storage tube. This was the electronic equivalent of an Etch-a-Sketch. You could draw very complicated images, but you had to electronically shake it up to erase it. It was very hard to draw solid images on a GLANCE G because it took huge numbers of vectors and ended up with display flicker. Storage tubes could handle solid images since there was no limit to the number of vectors, but the centers of the solid areas tended to fade. You could erase a single line on a GLANCE G by removing it from the display list. That wasn’t possible on a storage tube. It gave off a bright green flash when the screen was erased, which has been burned into many an aging programmer’s eyeballs.

Raster graphics is a completely different approach than vector graphics. It’s how television originally worked. The raster is a continually drawn pattern, as shown in Figure 6-54.

[!visual-conversion] Diagram showing raster scan pattern with horizontal lines and diagonal … Cropped from the scan (PDF page 220, printed p. 180): Diagram showing raster scan pattern with horizontal lines and diagonal retrace arrows.

Figure 6-54: A raster

The raster starts at the upper left and goes across the screen. Then a horizontal retrace takes it down to the start of the next line. Finally, a vertical retrace takes it back to the beginning once the last line is drawn.

This works very much like the starting-gun analogy I used earlier when discussing serial communications. Once the raster is off and running, all you have to do is to change the brightness at exactly the right time to get the image you want, as you can see in Figure 6-55.

[!visual-conversion] Diagram showing raster scan pattern with horizontal lines and gray … Cropped from the scan (PDF page 220, printed p. 180): Diagram showing raster scan pattern with horizontal lines and gray dots representing pixels.

Figure 6-55: House of raster graphics

I also used the analogy of a window screen back in “Digital Images” on page 173. A raster display is an actual screen, which means we can’t draw between the dots. This can result in unpleasant visual artifacts, such as the roof not looking quite right. That’s because the resolution of a typical raster display is fairly low—on the order of 100 dots per inch. The low resolution results in undersampling and aliasing similar to what we saw for digital images. Sufficient compute power now exists to make anti-aliasing commonplace using techniques such as supersampling.

Raster scanning is also used for things like fax machines, laser printers, and scanners. Pull up the lid of a scanner and watch it go. Wear sunglasses. Back when printers had more moving parts and were louder, people figured out how to play raster music on them by carefully choosing what to print.

Raster displays don’t use display lists, although display lists are still used behind raster displays. As we’ll see later, web pages are display lists. The OpenGL graphics language includes display lists, and support for the language is often included in graphics hardware. Monochrome displays use a piece of memory with 1 bit for each position on the raster. This was a huge amount of memory back in the day; now, it’s not such a big deal. Of course, that memory could get big fast. If you wanted a raster display that could do 256 different levels of gray, you’d need 8 bits of memory for each raster position.

Color was discovered in the Land of Oz and quickly made it onto the screen. Monochrome or grayscale displays were easy: all you had to do was to coat the inside of the screen with a layer of phosphor. Color displays needed three different color dots at each location on the raster—red, green, and blue—and three electron beams that could hit these spots with great precision. This meant you needed three times the display memory for a typical display.

Terminals have a way for you to input data in addition to the display that outputs data to you. You know them as the keyboard and mouse, the touchpad on your laptop, and the touchscreen on your phone and tablet.

Keyboards are pretty easy. They’re just a bunch of switches and some logic. A common way to build a keyboard is to put the key switches on a grid, multiplexing them kind of like in Figure 6-10. Power is sequentially applied to the rows of the grid, and the values of the columns are read out.

The mouse as we know it was invented by American engineer Douglas Engelbart (1925–2013) at the Stanford Research Institute. I mentioned in “Quadrature” on page 150 that you can make a mouse using a pair of quadrature encoders, one each for the xx and yy directions.

There are a lot of touchpad and touchscreen technologies. The main difference is that touchscreens have to be transparent so that the display can be seen. Touch devices are row- and column-scanning devices, like keyboards but on a much finer scale.

In this chapter, you learned about the interrupt system that allows processors to handle I/O efficiently. We talked about how various types of I/O devices work and how they interact with computers. We also discussed the complex area of sampling analog data so that it can be processed using digital computers. At this point, you know enough about how computers work, so starting with the next chapter, we’ll look at the relationship between hardware and software with the goal of learning how to write software that runs well on the hardware.