LFSR

Inputs

PinTypeDescription
ClockbitShift register on rising edge (0→1)
DevAddrbus8Device address — 0x1A for port 0xFA
IO_SELbitI/O select — must be 1 to read the LFSR

Outputs

PinTypeDescription
Databus8Current 8-bit pseudorandom value (0–255)

How It Works

A real die is honestly unpredictable. A digital circuit finds it easier to pretend: an LFSR is an 8-bit carousel of flip-flops where every tick the bits shift over, and XOR mixes the sum of several state bits into the freed slot. To the eye it looks like chaos, but inside it is strict mathematics.

The key property is determinism. The starting value 0x9C and the polynomial x⁸ + x⁶ + x⁵ + x⁴ + 1 pin down every next step: the new bit equals state[7] ⊕ state[5] ⊕ state[4] ⊕ state[3], and the remaining bits shift left. Example: 0x9C (156) → 0x39 (57) → 0x73 (115) — and so on through all 255 non-zero values in a row, after which the circle closes.

A nuance: the state 0x00 is a trap. XOR of all zeros is zero, and the register gets stuck there forever — so the seed must never be zero. The value is read like any I/O device of the course: IO_SEL = 1, DevAddr = 0x1A — port 0xFA.

Examples (clock sequence)

Clock tickData (hex)Data (dec)Comment
00x9C156the starting value (seed)
10x3957the first shift with XOR feedback
20x73115and so on — a new number every tick
2550x9C156the sequence closed; the cycle repeats

A dice roll from this sequence: LDA 250 reads the port, AND 7 trims it to 0–7, ADD 1 lifts it to 1–8.

Usage

Level 26 "Dice Roll" teaches reading the LFSR: LDA 250 puts a random byte into the accumulator, AND 7 trims it to the 0–7 range, ADD 1 lifts it to 1–8, and a conditional throw-away handles the extra values. In level 29 the food coordinates of Snake are born the same way: AND 15 yields a number from 0 to 15 — exactly the size of the playfield.

A concrete use: clock the LFSR on every Clock tick continuously, and read the port only at the moment of choice — then the "randomness" depends on which very tick the program peeked into the register. The same trick works for enemy behavior and any random events in games built on the course CPU.

Build it yourself →

Related components

Related articles

Frequently Asked Questions

How does an LFSR generate randomness?

It shifts a register with XOR feedback. The sequence is deterministic but looks random.

What happens if the seed is zero?

The LFSR gets stuck: XOR of all zeros is zero again, and the register never moves away from 0x00.

How many different values does an LFSR produce?

255: every byte from 0x01 to 0xFF appears once per period, after which the sequence repeats from the start.