Sikau

How computers work · Day 8 · about 35 min

Memory: clocks and registers

How a circuit remembers: rising clock edges, registers and counters.

Circuits that remember

Gates forget: change the input and the output changes. Wire two gates in a loop and the circuit holds its state — a latch. Add a clock — a signal ticking 0,1,0,1 billions of times a second — and you get a flip-flop that only listens at the moment the clock rises. A row of them is a register.

Edges, not levels

A camera with a shutter: the scene keeps changing, but the photo only captures the instant the button goes down. The rising clock edge is the button.

function makeRegister(bits) {
  const mask = 2 ** bits - 1;
  let value = 0;
  let lastClock = 0;
  return {
    tick(clock, load, d) {
      if (clock === 1 && lastClock === 0 && load === 1) value = d & mask;
      lastClock = clock;
    },
    get value() {
      return value;
    },
  };
}

function makeCounter(bits) {
  const size = 2 ** bits;
  let value = 0;
  let lastClock = 0;
  return {
    tick(clock, reset) {
      if (clock === 1 && lastClock === 0) value = reset === 1 ? 0 : (value + 1) % size;
      lastClock = clock;
    },
    get value() {
      return value;
    },
  };
}

The rest of this lesson

  • Why the clock existsexplain
  • A counter from a registerexplain
  • When does it store?predict
  • Memory vocabularymatch
  • Clocked memorywrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work