Talking over each other.

In the last chapter, two messages that overlapped were both damaged. This chapter shows how many transmitters can use the same frequency, which is the same spot on the radio dial, at the same moment and still be read separately.

Picture a party where a dozen conversations are going on in one room. If every group is speaking a different language, something useful happens. You can follow the conversation in your own language, and the rest blurs into background chatter. Every voice is in the air at once, mixed together, and what lets you pull one of them out is knowing what to listen for.

Radio can do the same. The idea is to give each transmitter its own long pattern, called a code, and to choose the codes so that they have almost nothing in common with one another. A receiver that searches for one code with the matched filter then gets a strong response from its own transmitter and almost none from the others. To that receiver, the other transmitters amount to a little extra noise.

This is how GPS works. Every GPS satellite broadcasts on the same frequency at the same time, each with its own code of 1,023 steps, and your phone separates them by searching for each code in turn. The general technique is called spread spectrum, for a reason that section 2 will show. One early form of it was patented in 1942 by the film actress Hedy Lamarr and the composer George Antheil. They proposed steering a torpedo with a radio signal that jumped from frequency to frequency in a secret pattern, so that an enemy who did not know the pattern could not block it. When the technique is used to let many users share one frequency it is called CDMA, for code division multiple access, and it carried the calls on many mobile phone networks of the 1990s and 2000s.

The sections below build the technique in order: first two codes that ignore each other, then how a code carries a message, and then the air with up to sixteen transmitters sending at once.

1. Two codes that ignore each other

The thirteen-step pattern of chapter 2 had a valuable property. Slid across a copy of itself, it gave 13 when lined up and almost nothing anywhere else. For two transmitters to share the air, the same has to hold between different codes. Code A slid across code B must give almost nothing at every position, lined up or not. If it does, a receiver hunting for A will hardly notice B.

There is a family of codes built to do exactly this. They are called Gold codes, after Robert Gold, who published them in 1967. Choose two of them below. The left chart slides code A across a copy of itself, and the right chart slides code A across code B. Each colored square is one step of a code, cyan for up and rose for down.

code A

code B

A against itself
A against B

Drag code B until it is the same as code A, and a spike appears in the right chart. The receiver could no longer tell the two apart. With any other choice the right chart stays low, and it stays low by guarantee. For Gold codes of 31 steps the total never passes 9, and for codes of 127 steps it never passes 17. That guarantee is what makes the family useful. There are 33 different codes of length 31 and 129 of length 127, and whichever two you hand out, you know in advance the worst they can do to each other.

Where the codes come from. Each code is produced by a very small machine: a row of memory cells, each holding a 1 or a 0. At every tick, each cell passes its contents to the cell on its right, and the cell at the left end is refilled with a value worked out from two or three of the others. The stream that falls off the right end looks random, but the machine is completely predictable, so anyone with the same machine gets the same stream. A machine with five cells runs for 31 steps before it repeats, and one with ten cells runs for 1,023, which is where the GPS number comes from. Combining the streams of two such machines, with one of them delayed, gives a Gold code, and each different delay gives a different member of the family. The programs at the end of this chapter build them in a dozen lines.

2. Spreading every bit becomes the whole code

Here is how a transmitter uses its code to carry a message. To send a 1, it sends the entire code. To send a 0, it sends the entire code upside down, with every up step swapped for a down step. A message of eight bits is the code sent eight times over, right side up or upside down according to the bits.

the bits 1 0 1 1 0 0 1 0, each sent as a whole coderight side up for a 1, upside down for a 0

The cost is plain to see. Sending one bit now takes 31 steps, where chapter 3 took one. Either the message goes 31 times slower, or the steps go 31 times faster. Real systems choose faster steps, and that has a consequence. A signal that changes quickly takes up a wider stretch of the radio dial than one that changes slowly, in the same way that a sharp click contains a wide range of pitches while a long steady note has only one. So the signal is spread across far more of the dial than its message needs. That is the "spread" in spread spectrum.

At the other end, the receiver runs the matched filter of chapter 2 with code A as its copy. Once in every 31 steps a spike appears. If the spike points up, the bit was a 1, and if it points down, the bit was a 0. Any other transmitter's signal, compared against code A, adds up to something small, limited by the guarantee from section 1. To receiver A, transmitter B is noise, and only a little of it.

3. Everyone at once the shared air

Below, every transmitter is on the air at the same time. Each has its own Gold code, and each began at a different moment, unknown to the receiver. All of their signals are added together, along with noise. The receiver chooses one code and slides its copy along the air to find that transmitter's timing. Then it reads one bit for every repeat of the code. Add transmitters and watch for the errors.

the air
how many of the air's samples fall at each height
the receiver's result for the chosen code
codebits sentbits readwrong bits

Before the experiments, look at the second chart, which counts how many of the air's samples fall at each height. Set the transmitters to one and the noise to zero, and the air has only two heights, up and down, so the chart shows two bars. Add transmitters and more heights appear, because sometimes the transmitters agree and pile up, and sometimes they disagree and cancel. By sixteen, the bars have taken on the bell shape drawn over them, which is the shape that pure noise makes.

That bell is worth a moment. Whenever many unrelated things are added together, the total tends toward the same bell-shaped spread, whatever the things were. It is why the heights of people and the errors in careful measurements follow that curve. For radio it has a blunt consequence. To anyone who lacks the codes, a crowd of transmitters is the same thing as noise. The receiver below the chart can pull one of them out only because it knows that one's code.

Now there are three things to try, in this order.

Pile them on. With codes of 31 steps and the noise at zero, four transmitters read cleanly, or nearly so. Push toward sixteen and errors appear, even with no noise at all. Each of the other transmitters adds only a little to the receiver's result, but the little amounts add up, and with enough of them the sum rivals the spike of 31 that the receiver is looking for. Now switch to codes of 127 steps. The same sixteen transmitters are read cleanly again. A longer code leaves room for more transmitters to overlap. The price is the one from section 2: four times as many steps for each bit means four times as much of the dial.

Make one louder. While listening to transmitter 2, drag the slider that makes transmitter 1 louder. When everyone was equally loud, the most that transmitter 1 could add to the result was 9, against a spike of 31. Make it ten times stronger and that 9 becomes 90, which buries the spike. This is called the near-far problem, and it is what makes the technique hard in practice. It is the party again: you can follow your own language through a room full of chatter, until someone standing next to you starts to shout. A phone beside a cell tower would drown out a phone at the edge of town. So those phone networks told every phone, hundreds of times a second, to turn its power up or down until all of them arrived at the tower equally strong. GPS escapes the problem because its satellites are all about the same distance away.

Listen to the loud one. Switch the receiver to transmitter 1 while it is still loud. It reads perfectly, which shows that the air itself was fine all along. The loud signal was a problem only for receivers that wanted something else.

Why the errors arrive sooner than the guarantee suggests. The guarantee in section 1 covers one whole code slid against another whole code. Here the transmitters did not start together, so while your receiver is adding up one of its bits, a neighbor may switch from one bit to the next partway through. What your receiver sees from that neighbor is then part of a code right side up followed by the rest of it upside down, a combination the guarantee never covered. Real systems live with this. It is one reason that 31 steps is a toy, and GPS uses 1,023.

4. How much room is there the arithmetic

The demonstration comes down to a few lines of arithmetic. Here L is the number of steps in the code, A is the strength of each transmitter and K is the number of transmitters on the air.

the wanted spike        L x A            every step of the right code agrees
one other transmitter   at most c x A    c is 9 when L is 31, and 17 when L is 127
K transmitters          the wanted spike is L x A. the others together add roughly
                        A x sqrt(K - 1) x sqrt(L), since each one behaves like noise
room on the air         the number of transmitters that fit grows in step with L
gain from the code      L times in power: 15 dB at 31 steps, 21 dB at 127, 30 dB at 1,023
a louder neighbor       one that is P times stronger does P times the damage

The line about room is the one to remember. The number of transmitters that can share the air grows along with the length of the code. Double the steps for each bit and roughly twice as many can overlap, at the cost of twice as much of the dial. GPS uses codes of 1,023 steps for about thirty satellites and has room to spare. The same length is also what makes GPS possible at all. The opening story said its signal arrives about a hundred times weaker than the receiver's hiss, and adding up 1,023 steps lifts the pattern about a thousand times in power, which carries it clear.

Long codes change two other things. Finding the signal takes longer, because the receiver has to try every starting position, and for each of those, every guess at the slip described in chapter 2. With 1,023 positions and a few dozen guesses there are tens of thousands of combinations to test, which is why an older GPS receiver switched on in a new place could take a minute or more to find itself.

A long code also protects against deliberate interference as well as against neighbors. A strong signal on a single frequency, sent to block the receiver, is treated by the adding-up exactly as another transmitter would be, and it shrinks by the same amount. That protection is what Lamarr and Antheil were after in 1942, and it is why armed forces were using the technique long before phone companies were.

A preamble and a code are one idea at two sizes. In chapter 3 a short pattern sat in front of plain bits, and only the pattern was protected by the adding-up. Here the pattern runs through the whole message, so every bit is protected, and every repeat of the code also marks the timing, as a preamble would. Real systems use both: a long code for the whole transmission, and a short known message at the front so the receiver can tell where the data begins.

5. The programs building codes, sending and receiving

In these programs a chip means one step of a code, which is the engineers' word for it, and an m-sequence is the stream produced by one of the small machines described in section 1.

building the codes

/* An m-sequence from a linear feedback shift register.
   taps[] holds the polynomial powers: {5, 2} means x^5 + x^2 + 1.
   Output is +1 / -1 chips, length 2^n - 1. */
void msequence(const int *taps, int ntaps, signed char *out)
{
    int n = taps[0], len = (1 << n) - 1;
    unsigned reg = 1;                              /* any nonzero seed */
    for (int i = 0; i < len; i++) {
        out[i] = (reg & 1) ? 1 : -1;
        unsigned fb = 0;
        for (int t = 0; t < ntaps; t++) fb ^= (reg >> (n - taps[t])) & 1;
        reg = (reg >> 1) | (fb << (n - 1));
    }
}

/* Gold code k from a preferred pair: a chip-by-chip product of a and b shifted by k. */
void gold(const signed char *a, const signed char *b, int len, int k, signed char *out)
{
    for (int i = 0; i < len; i++) out[i] = a[i] * b[(i + k) % len];
}

/* preferred pairs:  31 chips: {5,2} and {5,4,3,2}     127 chips: {7,3} and {7,3,2,1}
                   1023 chips (GPS C/A): {10,3} and {10,9,8,6,3,2}                     */
/// An m-sequence from a linear feedback shift register.
/// `taps` holds the polynomial powers: [5, 2] means x^5 + x^2 + 1.
pub fn msequence(taps: &[u32]) -> Vec<i8> {
    let n = taps[0];
    let len = (1usize << n) - 1;
    let mut reg: u32 = 1;
    (0..len).map(|_| {
        let chip = if reg & 1 == 1 { 1 } else { -1 };
        let fb = taps.iter().fold(0, |acc, &t| acc ^ ((reg >> (n - t)) & 1));
        reg = (reg >> 1) | (fb << (n - 1));
        chip
    }).collect()
}

/// Gold code k from a preferred pair.
pub fn gold(a: &[i8], b: &[i8], k: usize) -> Vec<i8> {
    (0..a.len()).map(|i| a[i] * b[(i + k) % a.len()]).collect()
}
import numpy as np

def msequence(taps):
    """taps are polynomial powers: [5, 2] means x^5 + x^2 + 1. Returns +1/-1 chips."""
    n, length = taps[0], (1 << taps[0]) - 1
    reg, out = 1, []
    for _ in range(length):
        out.append(1 if reg & 1 else -1)
        fb = 0
        for t in taps:
            fb ^= (reg >> (n - t)) & 1
        reg = (reg >> 1) | (fb << (n - 1))
    return np.array(out)

def gold(a, b, k):
    """Gold code k from a preferred pair: a times b rolled by k."""
    return a * np.roll(b, -k)

a, b = msequence([5, 2]), msequence([5, 4, 3, 2])
family = [gold(a, b, k) for k in range(31)] + [a, b]      # 33 codes

sending and receiving

/* Spread: each data bit becomes one full copy of the code, sign by the bit. */
void spread(const unsigned char *bits, int nbits, const signed char *code, int len, float *out)
{
    for (int b = 0; b < nbits; b++) {
        float sign = bits[b] ? 1.0f : -1.0f;
        for (int i = 0; i < len; i++) out[b * len + i] = sign * code[i];
    }
}

/* Despread: correlate with the code at the known timing offset, one bit per period. */
void despread(const float *x, int n, const signed char *code, int len, int offset,
              unsigned char *bits, int nbits)
{
    for (int b = 0; b < nbits; b++) {
        float sum = 0.0f;
        for (int i = 0; i < len; i++) {
            int j = offset + b * len + i;
            if (j < n) sum += x[j] * code[i];
        }
        bits[b] = sum >= 0.0f ? 1 : 0;
    }
}

/* Finding the offset is chapter 2 again: correlate one full period of the code against
   the air and take the position of the largest |peak|. */
import numpy as np

def spread(bits, code):
    """Each bit becomes one full copy of the code, sign by the bit."""
    signs = np.where(np.asarray(bits) == 1, 1.0, -1.0)
    return np.outer(signs, code).ravel()

def acquire(x, code):
    """Timing offset of the strongest |peak| within one code period."""
    y = np.correlate(x[:2 * len(code)], code, mode="valid")
    return int(np.argmax(np.abs(y)))

def despread(x, code, offset, nbits):
    """One bit per code period, starting at offset."""
    L = len(code)
    periods = x[offset:offset + nbits * L].reshape(nbits, L)
    return (periods @ code >= 0).astype(int)