Y
Published on

Clock and Timing Explained The Heartbeat of the Computer

Authors
  • avatar
    Name
    Yinhuan Yuan
    Twitter

Clock and Timing Explained: The Heartbeat of the Computer

Let me explain the clock system from the ground up - this is the heartbeat that keeps everything synchronized!


What is a Clock? (The Foundation)

The Fundamental Problem

Imagine a marching band without a conductor:

Band Member 1: *plays note*
Band Member 2: *plays different note* (2 seconds later)
Band Member 3: *plays yet another note* (5 seconds later)
Band Member 4: *still preparing instrument*

Result: CHAOS! Not music!


Now with a conductor keeping time:

Conductor: "1... 2... 3... 4..."
ALL members: *play together on beat 1*
ALL members: *rest on beat 2*
ALL members: *play together on beat 3*

Result: BEAUTIFUL MUSIC!

The computer is the same:
──────────────────────────

Without a clock:
├─ Registers update at random times
├─ ALU outputs change unpredictably
├─ Memory reads/writes collide
├─ Control signals arrive out of order
└─ TOTAL CHAOS!
With a clock:
├─ Everything changes on the same beat
├─ Predictable timing
├─ Synchronized operation
└─ WORKING COMPUTER!

What a Clock Actually Is

A clock is a SQUARE WAVE - a signal that oscillates:

Voltage
  5V ─┐     ┌─────┐     ┌─────┐     ┌─────
      │     │     │     │     │     │
      │     │     │     │     │     │
  0V  └─────┘     └─────┘     └─────┘
      
      ◄─ T ─►     ◄─ T ─►     ◄─ T ─►
      (period)

Key Parameters:
───────────────

Period (T):
├─ Time for one complete cycle
├─ Example: 125ns
└─ Determines how fast computer runs

Frequency (f):
├─ f = 1/T
├─ Number of cycles per second
├─ Example: 8 MHz = 8 million cycles/sec
└─ "Megahertz" = millions per second

Duty Cycle:
├─ Percentage of time HIGH
├─ Usually 50% (equal HIGH and LOW)
└─ Symmetrical square wave


Why Square Wave?
────────────────

Sharp edges:
├─ Clear transition from 0 to 1
├─ Components know EXACTLY when to act
├─ No ambiguity
└─ Digital systems need clean edges!

High: 5V (logic 1)
Low:  0V (logic 0)
Nothing in between (in ideal case)

The Clock's Job

The clock signal goes to EVERY sequential component:

    CLOCK ──┬──► A Register (U1-U2)
            ├──► D Register (U3-U4)
            ├──► PC Counter (U6-U9)
            ├──► RAM Control
            └──► (Any other flip-flops)


On each clock edge (rising or falling):
────────────────────────────────────────

1. Registers CAPTURE new data
   ├─ Whatever is on their D inputs
   ├─ Gets stored in flip-flops
   └─ "Sampling moment"

2. Counters INCREMENT
   ├─ PC adds 1 (or loads new value)
   └─ Automatic counting

3. State machines ADVANCE
   ├─ Move to next state
   └─ (Not used much in simple Hack)

Between clock edges:
────────────────────
├─ Data propagates through combinational logic
├─ ALU computes
├─ Control unit decodes
├─ Memory accesses
└─ Everything settles to new values

Then next clock edge:
─────────────────────
└─ Capture new data and repeat!


The Clock Creates Discrete Time Steps:
───────────────────────────────────────

Without clock: Continuous analog chaos
With clock: Discrete digital steps

Time: ─┬──┬──┬──┬──┬──┬──┬──
       │  │  │  │  │  │  │
       0  1  2  3  4  5  6  (cycles)
       
Each cycle is one "instruction time"
Computer advances one step per cycle
Clear, predictable, synchronized!

Clock Generation: The 555 Timer

Why Use a 555 Timer?

Options for Clock Generation:
──────────────────────────────

Option 1: Crystal Oscillator Module
────────────────────────────────────
├─ Pre-built oscillator
├─ Very accurate (10-100 ppm)
├─ Fixed frequency
└─ Cost: $2-5

Pros: Dead simple (3 pins: VCC, GND, OUT)
Cons: Fixed frequency, can't adjust


Option 2: Crystal + Gates
──────────────────────────
├─ Crystal + 74HC04 inverters
├─ Very accurate
├─ Fixed frequency
└─ Cost: $1-2

Pros: Accurate, cheap
Cons: Fixed frequency, more complex


Option 3: 555 Timer (OUR CHOICE!)
──────────────────────────────────
├─ Classic timer IC
├─ Adjustable frequency (pot or resistor)
├─ Simple circuit
├─ Accuracy: ~2-5% (good enough!)
└─ Cost: $0.30

Pros:
Simple circuit (few components)
Adjustable frequency (great for experimentation!)
Can slow down to single-step for debugging
Very common, available everywhere
Educational (you learn how it works)
Cheap!

Cons:
Not super accurate (but fine for hobby project)
Frequency drifts with temperature
Not suitable for precision timing

For Hack computer: 555 is PERFECT!

Inside the 555 Timer

555 Internal Block Diagram (Simplified):

VCC ──┬──────────────────────────────────┐
      │                                  │
      │  ┌───────────────────────────┐   │
      │  │  Voltage Divider          │   │
  (Three 5kΩ resistors)    │   │
      │  │                           │   │
      │  │   VCC ─┬─ 5kΩ ─┬─ 5kΩ ─┬─│─ GND
      │  │        │       │       │ │   │
      │  │     2/3 VCC  1/3 VCC   │ │   │
      │  │        │       │       │ │   │
      │  └────────┼───────┼───────┼─┘   │
      │           │       │       │     │
      │           ▼       ▼       ▼     │
      │        ┌──────────────────┐     │
      │        │   Comparators    │     │
THRESH├────────┤► Upper (2/3 VCC)
(pin 6)│       │                  │     │
      │        │   Lower (1/3 VCC)│     │
TRIG  ├────────┤► Lower (1/3 VCC)
(pin 2)│       └────────┬─────────┘     │
      │                │                │
      │                ▼                │
      │        ┌────────────────┐       │
      │        │   SR Flip-Flop │       │
      │        │                │       │
      │        │  S         Q   ├───┬───┼─► OUTPUT
      │        │                │   │      (pin 3)
      │        │  R        !Q   │   │   │
      │        └────────────────┘   │   │
      │                             │   │
DISCH ├─────────────────────────────┘   
(pin 7)        (Discharge transistor)      │                                 │
      └─────────────────────────────────┘

The "555" name comes from the three 5kΩ resistors!


How It Works (Astable Mode):
─────────────────────────────

1. Capacitor charges through resistors
2. When voltage reaches 2/3 VCC:
   ├─ Upper comparator triggers
   ├─ Flip-flop resets
   ├─ Output goes LOW
   └─ Discharge pin activates

3. Capacitor discharges through discharge pin
4. When voltage falls to 1/3 VCC:
   ├─ Lower comparator triggers
   ├─ Flip-flop sets
   ├─ Output goes HIGH
   └─ Discharge pin deactivates

5. Cycle repeats forever!

This creates oscillation!

555 Astable Circuit for Hack Computer

Standard 555 Astable Oscillator:

        VCC (+5V)
         ├──────────────────┐
         │                  │
         ▼                  │
        ┌────┐              │
R1 │ 10kΩ         │
        └─┬──┘              │
          │                 │
          ├─────────┬───────┤ (pin 8: VCC)
          │         │       │
          ▼         │   ┌───┴──────┐
        ┌────┐      │   │          │
R2 │ 1kΩ  ├───┤7  DISCH        └─┬──┘      │   │          │
          │         │   │  555          ├─────────┼───┤6  THRESH          │         │   │          │
          │         └───┤2  TRIG          │             │          │
          │             │  OUTPUT 3├────► CLOCK OUT
          │             │          │
          │             │  RESET  4├──┬─► VCC (not reset)
          │             │          │  │
          │             │  CTRL   5├──┤─► (0.01µF to GND)
          │             │          │  │
          │             │  GND    1├──┼─► GND
          │             └──────────┘  │
          ▼                           │
        ┌────┐                        │
C10.1µF        └─┬──┘                        │
          │                           │
         GND ─────────────────────────┘


Component Values:
─────────────────

R1: 10 (charge resistor)
R2: 1 (discharge resistor)
C1: 0.1µF = 100nF (timing capacitor)

Frequency Calculation:
──────────────────────
f = 1.44 / ((R1 + 2×R2) × C1)
  = 1.44 / ((10k + 2k) × 0.1µF)
  = 1.44 / (12k × 0.1µF)
  = 1.44 / 1.2ms
  = 1.2 kHz

Wait, that's way too slow!

For 8 MHz, we need:
8 MHz = 1.44 / ((R1 + 2×R2) × C)

Rearrange:
(R1 + 2×R2) × C = 1.44 / 8MHz
                = 1.44 / 8,000,000
                = 0.18 µs
                = 180 ns

If C = 100pF (0.0001µF):
R1 + 2×R2 = 180ns / 100pF = 1.8kΩ

Let's use:
├─ R1 = 680Ω
├─ R2 = 560Ω
└─ C1 = 100pF

Check:
f = 1.44 / ((680 + 1120) × 100pF)
  = 1.44 / (1800 × 100pF)
  = 1.44 / 180ns
  = 8 MHz

Actual Circuit for 8 MHz:
──────────────────────────

        VCC (+5V)
         ├──────────────────┐
         │                  │
         ▼                  │
        680Ω                │
         │                  │
         ├─────────┬────────┤
         │         │    ┌───┴──────┐
         ▼         │    │   555        560Ω       ├────┤7         │         │    │          │
         ├─────────┼────┤6,2         │         │    │          │
         │         │    │        3 ├─► 8 MHz
         │         │    │          │
         │         │    │        4 ├─► VCC
         │         │    │          │
         │         │    │        5 ├─► 0.01µF
         ▼         │    └──────────┘
       100pF       │
         │         │
        GND ───────┴────


Duty Cycle:
───────────
Duty = (R1 + R2) / (R1 + 2×R2)
     = (680 + 560) / (680 + 1120)
     = 1240 / 1800
     = 69%

Not quite 50%, but close enough!

For better 50% duty cycle, use additional flip-flop
to divide frequency by 2 (covered later).

Adjustable Clock (Variable Frequency)

For Experimentation and Debugging:

Replace R2 with potentiometer!

        VCC (+5V)
         ├──────────────────┐
         │                  │
         ▼                  │
        ┌────┐              │
R1 │ 1kΩ          │
        └─┬──┘              │
          │                 │
          ├─────────┬───────┤
          │         │   ┌───┴──────┐
          │         │   │   555          │    ┌────┴───┤7          │    │ POT    │          │
          │    │ 0-100k ├───┤6,2          │    └────┬───┤          │
          │         │   │        3 ├─► VARIABLE CLOCK
          ├─────────┘   │          │
          │             │        4 ├─► VCC
          │             └──────────┘
        ┌────┐
C11µF
        └─┬──┘
         GND


Frequency Range:
────────────────

Pot at 0Ω (minimum):
f_max = 1.44 / ((1k + 0) × 1µF)
      = 1.44 kHz

Pot at 100 (maximum):
f_min = 1.44 / ((1k + 200k) × 1µF)
      = 1.44 / 201ms
      = 7.16 Hz

Range: 7 Hz to 1.4 kHz
Perfect for debugging!

Can even slow to <1 Hz for single-stepping!


With Switch for Fast/Slow:
───────────────────────────

    VCC
     ├─ R1 (1kΩ) ─┬─── Switch ───┐
     │            │               │
     │            │              555
     │            │             pin 7
     │            │
┌──┴──┐  (Fast)
     │         │ 1kΩ │
     │         └──┬──┘
     │            │
┌──┴──┐  (Slow)
     │         │100k │
     │         └──┬──┘
     │            │
     ├────────────┴─── 555 pin 6,2
    Cap
    GND

Switch position:
├─ Up: Fast mode (~8 MHz for running)
└─ Down: Slow mode (~10 Hz for debugging)

Perfect for development!

Clock Distribution Network

The Problem: Fan-Out

The clock needs to reach MANY places:

    CLOCK ──┬──► A Register (U1, U2)
            ├──► D Register (U3, U4)
            ├──► PC (U6, U7, U8, U9)
            ├──► Control logic
            └──► RAM control

Total loads: ~12-15 clock inputs!


The Problem:
────────────

555 output:
├─ Can source: 200mA (impressive!)
├─ Can sink: 200mA
└─ Seems like plenty...

BUT each 74HC input:
├─ Input current: <1µA (DC)
├─ Input capacitance: ~10pF
└─ CAPACITANCE is the issue!

Total capacitive load:
15 inputs × 10pF = 150pF

Plus PCB trace capacitance:
10cm trace @ 100pF/m = 10pF

Total: ~160pF

When driving capacitive load:
────────────────────────────

         5V ─┐
            │ \  Rise time = R × C
            │  \
            │   \___
         0V     │
                └─ slow edge!

555 output impedance: ~50Ω
Rise time = 50Ω × 160pF = 8ns

That's acceptable, BUT...
PCB traces add inductance too!
Real rise time: 15-20ns

Solution: Clock Buffer

Use 74HC04 Hex Inverter as Buffer:

    555 ──► [74HC04] ──┬──► Group 1 (A, D registers)
           (inverter)                       ├──► Group 2 (PC counter)
                       ├──► Group 3 (Control)
                       └──► Group 4 (Others)


74HC04 Specifications:
──────────────────────
├─ Output drive: 25mA (much better than needed)
├─ Propagation delay: ~10ns
├─ Rise time: <5ns (into reasonable load)
└─ Can easily drive 10+ loads

Better yet, since 74HC04 has 6 inverters:
──────────────────────────────────────────

Use TWO stages (double inversion = no inversion):

    555 ──► [INV1] ──► [INV2] ──┬──► Clock Out A
                                ├──► Clock Out B
                                ├──► Clock Out C
                                └──► Clock Out D

INV1: Buffer stage (strengthens signal)
INV2: Distribution stage (fans out)

Each output of INV2 drives 3-4 loads maximum
Perfect signal integrity!

Complete Clock Buffer Circuit:
───────────────────────────────

         555        74HC04
        Output      U_CLK
          ├─────┬───┤1   2├──┬───► CLK_A (to A, D registers)
          │     │   └─────┘  │
          │     │            ├───► CLK_B (to PC)
          │     │            │
          │     └───┤3   4├──┴───► CLK_C (to control)
          │         └─────┘
          └─────────┤5   6├──────► CLK_D (spare)
                    └─────┘

Pin numbering (74HC04 DIP-14):
├─ Pins 1,3,5,9,11,13: Inputs
├─ Pins 2,4,6,8,10,12: Outputs
├─ Pin 7: GND
└─ Pin 14: VCC

Benefits:
─────────
Strong drive capability
Clean edges
Multiple outputs (reduced loading each)
Simple and cheap (one IC)
Low propagation delay

Clock Distribution Topology

Star Topology (BEST for Clock):

         555 Timer
         [Buffer]
       ┌─────┼─────┬─────┐
       │     │     │     │
       ▼     ▼     ▼     ▼
    ┌────┐┌────┐┌────┐┌────┐
A  ││ D  ││ PC ││Ctrl│
    │Reg ││Reg ││Cnt ││ Unit│
    └────┘└────┘└────┘└────┘

Equal length traces from buffer to each component!

Advantages:
───────────
Equal delay to all components
No clock skew (all arrive same time)
Best signal integrity
Easy to route


Tree Topology (Alternative):

         555 Timer
         [Buffer]
       ┌─────┴─────┐
       ▼           ▼
   [Buffer 1]  [Buffer 2]
       │           │
   ┌───┴───┐   ┌───┴───┐
   ▼       ▼   ▼       ▼
  A,D     PC  Ctrl   Others

Advantages:
───────────
Lower loading per buffer
Cleaner signals
Easier routing (hierarchical)

Disadvantages:
──────────────
More gates = more delay
Potential for skew between branches


Daisy Chain (BAD for Clock!):

    555 ──► [A] ──► [D] ──► [PC] ──► [Ctrl]

Problems:
─────────
Different delay to each component
Clock skew (components act at different times)
Cumulative degradation
NEVER USE FOR CLOCK!


Recommended for Hack:
──────────────────────

Simple star with 74HC04 buffer
├─ One 74HC04 IC
├─ Four outputs
├─ Drives 3-4 loads each
└─ Simple and effective ✓

Timing Fundamentals

Setup and Hold Times

These are CRITICAL concepts!

What Are Setup and Hold Times?
───────────────────────────────

Every flip-flop (register) has timing requirements:

         ┌── Setup Time ──┐ ┌─ Hold Time ─┐
         │                 │ │             │
Data: ───┴─────────────────┴─┴─────────────┴───
STABLE       │ │   STABLE         │                 │ │             │
         │                 │ │             │
CLK:  ───────────╗         ╚═══╗           ────
                 ╚═════════════╝
                   Clock Edge
                   (sampling moment)


Setup Time (t_su):
──────────────────
├─ Data must be STABLE before clock edge
├─ Minimum time: typically 5-20ns
├─ If violated: might capture wrong data!
└─ "Data must arrive early"

Hold Time (t_h):
────────────────
├─ Data must stay STABLE after clock edge
├─ Minimum time: typically 2-10ns
├─ If violated: might capture transition!
└─ "Data must stay put briefly"


Why These Matter:
─────────────────

Inside a flip-flop:
┌─────────────────────────────┐
D input → Transistors           (gates opening)│                │            │
│                ▼            │
Storage Node           (capacitance)│                │            │
│                ▼            │
Q output       │
└─────────────────────────────┘

Setup time: Transistors need time to charge storage capacitance
Hold time: Storage node needs time to stabilize

If data changes too soon:
Partial charge on storage node
Uncertain final state
METASTABILITY! (covered later)


Example with 74HC574:
──────────────────────

From datasheet:
├─ t_su = 12ns (setup time)
├─ t_h = 3ns (hold time)
└─ t_co = 25ns (clock-to-output)

Valid timing:
             ┌─12ns─┐┌3ns┐
Data:  ──────┴──────┴┴───┴──────
                    ││
CLK:   ─────────╗   ││   ╔──────
                ╚═══╝╚═══╝
               Capture moment

Invalid timing (setup violation):
          ┌─5ns─┐  ◄── TOO SHORT!
Data: ────┴─────┴──────
CLK:  ──────────╗╔═════
                ╚╝
                
Result: GLITCH! Wrong data captured!

Propagation Delay

Every Logic Gate Has Delay:
────────────────────────────

Real gates are NOT instantaneous!

         Input
    ┌──────────────┐
Logic Gate       (AND, OR)    └──────┬───────┘
           │ ◄── Propagation delay (t_pd)
         Output


Example: 74HC08 (AND gate)
───────────────────────────

Datasheet specs:
├─ t_pd = 10ns (typical)
├─ t_pd = 15ns (maximum)
└─ Varies with load, voltage, temperature

Timing diagram:
───────────────

Input A:  ──╗     ╔═════
            ╚═════╝

Input B:  ═════════════  (already HIGH)

Output:   ══════════╗     ╔═════
                   ╚═════╝
                   │◄─ t_pd ─►│
                  Delay!

The output change LAGS the input change!


Cumulative Delay Through Path:
───────────────────────────────

Multiple gates in series ADD delays:

In ──► [Gate 1] ──► [Gate 2] ──► [Gate 3] ──► Out
        10ns         10ns         10ns

Total delay = 10 + 10 + 10 = 30ns


Real Example: ALU Carry Chain
──────────────────────────────

Bit 0 ──► [Adder] ──► Bit 1 ──► [Adder] ──► Bit 2 ──► [Adder]
           20ns                    20ns                  20ns
                      (carry)               (carry)

Total: 3 × 20ns = 60ns

For 16 bits: 4 × 20ns = 80ns
This is your CRITICAL PATH!

Critical Path Analysis

Critical Path = Longest Delay Path Through System

For Hack Computer:
──────────────────

Path 1: Register to Register (CRITICAL!)
─────────────────────────────────────────

Register A ──► ALU ──► Register D
    │           │          │
    ▼           ▼          ▼

Breakdown:
──────────
1. Clock edge                    t = 0ns
2. Register A output valid       t = 25ns (t_co)
3. Through X input mux           t = 37ns (+12ns)
4. Through ALU preprocessing     t = 52ns (+15ns)
5. ALU addition (carry chain)    t = 92ns (+40ns)
6. Through ALU postprocessing    t = 102ns (+10ns)
7. Setup time at Register D      t = 114ns (+12ns)
8. Clock edge (safe capture)     t = 114ns ✓

Total path: 114ns
Plus margin: 11ns
Clock period needed: 125ns minimum
Maximum frequency: 8 MHz

Path 2: Memory Read Path
─────────────────────────

Register A ──► RAM ──► X input ──► ALU ──► Register D
    │          │         │          │          │
    ▼          ▼         ▼          ▼          ▼

Breakdown:
──────────
1. Clock edge                    t = 0ns
2. Register A output             t = 25ns
3. RAM access time               t = 80ns (+55ns)
4. Through transceiver           t = 85ns (+5ns)
5. Through X mux                 t = 97ns (+12ns)
6. Through ALU (minimal)         t = 107ns (+10ns)
7. Setup time                    t = 119ns (+12ns)

Total: 119ns
Margin: 6ns (tighter!)
Still fits in 125ns ✓


Path 3: Instruction Fetch
──────────────────────────

PC ──► ROM ──► Control Unit ──► Control Signals
 │      │         │                   │
 ▼      ▼         ▼                   ▼

Breakdown:
──────────
1. PC output                     t = 25ns
2. ROM access                    t = 95ns (+70ns)
3. Control decode                t = 115ns (+20ns)

Total: 115ns
Fits easily!

The CRITICAL PATH determines max frequency:
────────────────────────────────────────────

Longest path: 119ns (memory read)
Add safety margin: 6ns
Clock period: 125ns
Frequency: 8 MHz
To go faster, need to:
├─ Use faster RAM (55ns → 45ns)
├─ Use faster logic (74HC → 74AC)
├─ Add pipeline stages (complex!)
└─ Or accept current speed (usually fine!)

Clock Quality Issues

Jitter

Jitter = Variation in Clock Edge Timing

Ideal clock:
────────────

    ╔═══╗   ╔═══╗   ╔═══╗   ╔═══╗
    ║   ║   ║   ║   ║   ║   ║   ║
════╝   ╚═══╝   ╚═══╝   ╚═══╝   ╚═══

Perfect spacing: T, T, T, T...


Real clock with jitter:
───────────────────────

    ╔═══╗   ╔═══╗ ╔═══╗    ╔═══╗
    ║   ║   ║   ║ ║   ║    ║   ║
════╝   ╚═══╝   ╚═╝   ╚════╝   ╚═══
    
    ◄─T─►◄─T─►◄T+►◄─T-─►
              edges move!


Types of Jitter:
────────────────

Period Jitter:
├─ Variation in clock period
├─ T varies slightly: 124ns, 126ns, 125ns...
└─ Causes: noise, power supply variation

Cycle-to-Cycle Jitter:
├─ Difference between adjacent periods
├─ Most critical for digital systems
└─ Typical: 1-5% of period

Long-term Jitter:
├─ Drift over many cycles
├─ Less critical for synchronous logic
└─ Important for communication


Effect on System:
─────────────────

Small jitter (1-2ns):
No problem! Margins absorb it
✓ 125ns ± 2ns = 123-127ns
Still meets timing

Large jitter (20ns):
Problem! May violate timing
✗ 125ns ± 20ns = 105-145ns
Setup times may fail!


555 Timer Jitter:
─────────────────
├─ Period jitter: ~2-5%
├─ At 8 MHz: 125ns ± 3ns
├─ Cycle-to-cycle: ~2ns
└─ Acceptable for Hack!
Crystal oscillator:
├─ Period jitter: ~0.01%
├─ Much better, but not needed
└─ Overkill for hobby project


Reducing Jitter:
────────────────
1. Clean power supply (filtered VCC)
2. Good decoupling capacitors (0.1µF at 555)
3. Short clock traces
4. Keep away from noisy signals
5. Use crystal if critical (not needed here)

Duty Cycle

Duty Cycle = Percentage of Time Clock is HIGH

         High Time
         ◄───────►
    ╔═══════╗     ╔═══════╗
    ║       ║     ║       ║
════╝       ╚═════╝       ╚═════
    ◄─────────T─────────►
        Period


Duty Cycle = (High Time / Period) × 100%


Ideal: 50% Duty Cycle
──────────────────────

    ╔═════╗     ╔═════╗
    ║     ║     ║     ║
════╝     ╚═════╝     ╚═════

High time = Low time = T/2
Perfect symmetry!

Benefits:
Equal setup time on both edges (if using both)
Predictable timing
Standard practice


555 Timer Natural Duty Cycle:
──────────────────────────────

Due to circuit topology:
Duty = (R1 + R2) / (R1 + 2×R2)

Can't naturally get exactly 50%!

Example with R1=680Ω, R2=560Ω:
Duty = (680 + 560) / (680 + 1120)
     = 1240 / 1800
     = 68.9%

Not terrible, but not ideal!


Fixing Duty Cycle:
──────────────────

Method 1: Use Divide-by-2
──────────────────────────

    555 ──► [74HC74] ──► 50% Duty Cycle Output
           (Flip-Flop)

74HC74 = Dual D Flip-Flop
Connect as divide-by-two:

         555 OUT ───► CLK
    ┌─────────▼──────────┐
    │      74HC74        │
    │                    │
Q ──────┐         │
    │          ▼         │
D ◄───┤NOT├───┐  │
    │          ▲     │  │
!Q ─────┘     │  │ ──► 50% Output
    │                └──┤
    └───────────────────┘

This divides frequency by 2:
├─ Input: 16 MHz (from 555)
├─ Output: 8 MHz (50% duty)└─ Perfect square wave!

Timing:
───────

555 Output:
    ╔═══╗ ╔═══╗ ╔═══╗ ╔═══╗
    ║   ║ ║   ║ ║   ║ ║   ║
════╝   ╚═╝   ╚═╝   ╚═╝   ╚═══
    16 MHz, 69% duty

74HC74 Output:
    ╔═══════╗       ╔═══════╗
    ║       ║       ║       ║
════╝       ╚═══════╝       ╚═══
    8 MHz, 50% duty ✓


Method 2: Use Additional Diode
───────────────────────────────

Add diode in parallel with R2:

        VCC
        R1
         ├─────────┬───555
         │         │
       ──┴──       │
      ─┤Diode├─────┘
       ──┬──
        R2
        Cap
        GND

Charge path: R1 (bypass diode)
Discharge path: R2 (through diode)

If R1 = R2, duty cycle ≈ 50%!

More complex, less common method.


For Hack Computer:
──────────────────

Option 1: Accept 69% duty cycle
├─ Works fine for edge-triggered flip-flops
├─ Simple
└─ Sufficient
Option 2: Use 74HC74 divider
├─ Perfect 50% duty cycle
├─ Slightly more complex
├─ If you want perfection
└─ Also works great ✓

I recommend: Just use 555 directly!
69% is fine for this application.

Rise and Fall Time

Real Signals Have Sloped Edges:

Ideal (impossible):
───────────────────

     5V ─┐     ┌─────
         │     │
         │     │  Instantaneous
    0V   └─────┘


Real (actual):
──────────────

     5V      ╱│     │╲
            ╱ │     │ ╲
           ╱  │     │  ╲  Slope!
    0V   ─╯   │     │   ╲─
              ◄─────►
             Rise time


Definitions:
────────────

Rise Time (t_r):
├─ Time for signal to go from 10% to 90%
├─ (not 0% to 100%, those are hard to measure)
└─ Typical 74HC: 5-10ns

Fall Time (t_f):
├─ Time for signal to go from 90% to 10%
├─ Usually similar to rise time
└─ Typical 74HC: 5-10ns


Why This Matters:
─────────────────

During transition:
├─ Signal is in "uncertain" region
├─ Neither HIGH nor LOW
├─ Different components may disagree!
└─ Can cause glitches


Slow edges cause problems:
──────────────────────────

If rise time = 50ns (too slow!):

     5V        ╱╱╱╱╱╱╱│
              ╱       │
             ╱        │
    0V   ───╯         │
            ◄────50ns────►

Problems:
Different gates trigger at different times
Ringing (oscillation) possible
Noise susceptibility (long uncertain period)
Multiple triggering of edge-sensitive circuits


Causes of Slow Rise Time:
──────────────────────────

1. High capacitive load
   RC time constant: t = R × C
   
   If R=100Ω, C=500pF:
   t = 100Ω × 500pF = 50ns
   Too slow!

2. Long PCB traces
   ├─ More capacitance
   ├─ More inductance
   └─ Transmission line effects

3. Weak driver
   ├─ High output impedance
   └─ Can't charge load quickly


Solutions:
──────────

1. Use buffer (74HC04)
   ├─ Strong output drive
   └─ Fast edges

2. Short clock traces
   ├─ Minimize capacitance
   └─ Star topology

3. Termination resistors
   ├─ For long traces (>30cm)
   ├─ Matches impedance
   └─ Usually not needed at 8 MHz

4. Schmitt trigger inputs
   ├─ Hysteresis
   ├─ Noise immunity
   └─ Clean up slow edges


Measuring Rise Time:
────────────────────

With oscilloscope:
├─ Measure 10% voltage: 0.5V
├─ Measure 90% voltage: 4.5V
├─ Time difference = rise time
└─ Should be <10ns for 8 MHz clock


For Hack at 8 MHz:
───────────────────

Clock period: 125ns
Rise time target: <10ns
└─ <10% of period ✓

555 + 74HC04 buffer:
├─ Rise time: ~6ns
├─ Fall time: ~6ns
└─ Excellent!

Metastability and Synchronization

The Metastability Problem

What is Metastability?
──────────────────────

Metastability occurs when flip-flop timing is violated!

Normal Operation:
─────────────────

Data changes well before clock:

Data: ───┴────────────────────┴───
                (stable)
CLK:  ─────────╗╔═════════════════
               ╚╝

Result: Clean capture, Q = 0

Timing Violation:
─────────────────

Data changes RIGHT AT clock edge:

Data: ──────────┬─────────────────
CLK:  ──────────╗╔═════════════────
                ╚╝
                Collision!

Result: METASTABLE STATE!


What Happens Inside:
────────────────────

Normal: Storage node charges to 0V or 5V
Metastable: Storage node stuck at ~2.5V!

     5V ────────────────
     2.5V ●════════  ◄── Stuck here!
     0V ────────────────

The flip-flop is "undecided"!
Neither 0 nor 1!


Observable Effects:
───────────────────

1. Extended settling time
   ├─ Normal: settles in 25ns
   └─ Metastable: may take 100ns+!

2. Oscillation
   ├─ Output oscillates rapidly
   ├─ Internal feedback fighting
   └─ Eventually settles to 0 or 1

3. Unpredictable output
   ├─ Could settle to 0
   ├─ Could settle to 1
   └─ Depends on noise!


Probability:
────────────

Metastability is RARE but POSSIBLE:

MTBF (Mean Time Between Failures):
MTBF = e^(t_r / τ) / (f_c × f_d)

Where:
├─ t_r: resolution time (time to settle)
├─ τ: time constant (device parameter ~1ns)
├─ f_c: clock frequency
└─ f_d: data change frequency

For typical values:
├─ 8 MHz clock
├─ Asynchronous input changes 1 MHz
├─ Resolution time = 20ns
└─ MTBF10^6 seconds = 11 days

Once every 11 days, might see glitch!
Not great for mission-critical system!

Synchronizer Circuits

Solution: Two-Stage Synchronizer
─────────────────────────────────

Use TWO flip-flops in series:

                    ┌─────┐      ┌─────┐
Async Input ───────►│ FF1 ├─────►│ FF2 ├─────► Sync Output
                    │     │      │     │
                CLK─┤>CLK─┤>                    └─────┘      └─────┘
                     Stage 1     Stage 2


How It Works:
─────────────

Stage 1 (FF1):
├─ Captures async input
├─ Might go metastable
├─ Gets full clock cycle to settle
└─ Usually settles within 1 cycle

Stage 2 (FF2):
├─ Samples FF1 output
├─ FF1 has had time to settle
├─ Clean, stable input
└─ No metastability!

Latency: 2 clock cycles
But: Reliable synchronization!


Probability Improvement:
────────────────────────

Single stage MTBF: 11 days
Two stage MTBF: 10^12 seconds = 31,000 years!

Much better!

Circuit Diagram (74HC74):
──────────────────────────

                    74HC74
              ┌─────────────────┐
              │                 │
Async Input ──┤D1           Q1  ├───┬─── Sync Output
              │                 │   │
              │                 │   │
          CLK─┤>CLK1            │   │
              │                 │   │
D2◄──┘
              │                 │
          CLK─┤>CLK2        Q2  ├───── (not used)
              │                 │
              └─────────────────┘

Both flip-flops clock simultaneously
Q1D2 connection creates two-stage sync


When to Use Synchronizers:
───────────────────────────

ALWAYS use for:
├─ External buttons/switches
├─ Asynchronous serial data
├─ Signals from different clock domains
└─ Any unsynchronized input

Never needed for:
├─ Internal synchronous signals
├─ Signals generated by same clock
└─ Properly synchronized data


For Hack Computer:
──────────────────

Internal signals: No sync needed
├─ All registers same clock
├─ All synchronous
└─ No metastability risk ✓

External inputs (if added):
├─ Reset button → synchronizer
├─ Manual clock step → synchronizer
├─ Serial input → synchronizer
└─ Required for reliability!

Reset Circuit

Power-On Reset (POR)

Why Need Reset?
───────────────

At power-up:
├─ Flip-flops contain RANDOM states
├─ PC could be 0x1234 (wrong!)
├─ Registers contain garbage
└─ Computer in unknown state

Need to FORCE known state:
├─ PC = 0 (start at beginning)
├─ Registers = 0 (optional)
└─ Clear state


Simple RC Reset:
────────────────

        VCC (+5V)
        ┌────┐
R10 (pull-up)
        └─┬──┘
          ├──────────► RESET (active LOW)
          │           to all /CLR pins
        ┌────┐
C10µF (delay capacitor)
        └─┬──┘
         GND


How It Works:
─────────────

At power-up (t=0):
├─ VCC rises from 0V to 5V
├─ Capacitor is discharged (0V)
├─ RESET = 0V (active!)
└─ All flip-flops clear

After delay:
├─ Capacitor charges through R
├─ RESET voltage rises
├─ When RESET > 3.5V: inactive
└─ System starts running


Timing:
───────

RC time constant: τ = R × C
                   = 10kΩ × 10µF
                   = 100ms

Voltage across C:
V(t) = VCC × (1 - e^(-t/τ))

At t = τ (100ms):
V = 5V × (1 - e^-1)
  = 5V × 0.63
  = 3.15V

At t = 2τ (200ms):
V = 5V × (1 - e^-2)
  = 5V × 0.86
  = 4.3V  (above threshold)

Reset duration: ~200ms
Plenty of time!

Voltage vs Time:
────────────────

 5V ───────────────────────────────
        ╱╱╱╱╱╱╱╱╱╱╱╱╱
 3.5V ─╱─────────────────  (Threshold)
 0V ─┘
    0ms   100ms   200ms

RESET = 0 (active) from 0-200ms
RESET = 1 (inactive) after 200ms


Problems with Simple RC:
─────────────────────────

1. Slow VCC rise:
   ├─ If power rises slowly
   ├─ Reset may be marginal
   └─ Unreliable startup

2. No manual reset:
   ├─ Can't reset after power-up
   └─ Need power cycle to reset

3. Noise sensitivity:
   ├─ Glitches on power line
   └─ Might trigger unwanted reset


Better Reset: Supervisor IC
────────────────────────────

Use dedicated reset supervisor chip:
Example: DS1233 or TL7705


         DS1233
         ┌───────┐
    VCC ─┤1    4 ├─ GND
         │       │
RESET├──► RESET OUT
3    (active LOW)
         │       │
         └───────┘

Features:
─────────
Monitors VCC continuously
Asserts reset if VCC drops
Guaranteed clean reset pulse
Debounced
Very reliable

Threshold: 4.5V (for 5V systems)
Reset delay: 250ms (built-in)
Cost: ~$1

Much better than RC!

Manual Reset Button

Adding Push Button Reset:
─────────────────────────

        VCC
        10 (pull-up)
         ├────────► RESET
        ─┴─  Push button
        ─┬─  (normally open)
        GND


Problem: Switch Bounce!
───────────────────────

Mechanical switches BOUNCE:

Button pressed:

RESET: ──╗╔╗╔╗╔╗╔╗╔═══════════
         ╚╝╚╝╚╝╚╝╚╝
         ◄──────────► 5-20ms
            Bouncing!

Each bounce looks like separate reset!
Could corrupt system state!


Solution 1: Hardware Debounce
──────────────────────────────

Add RC filter:

        VCC
        10kΩ
         ├────────┬────► RESET
         │        │
        ─┴─      ┌┴┐
    Switch       │ │ 100nF (debounce cap)
        ─┬─      └┬┘
         │        │
        GND      GND

Capacitor filters out bounces
Time constant = 10kΩ × 100nF = 1ms
Smooths transitions ✓


Solution 2: Schmitt Trigger
────────────────────────────

Use 74HC14 (Schmitt trigger inverter):

        VCC
        10kΩ
         ├────────┬────► RESET
         │        │
        ─┴─    ┌──┴──┐
    Switch     │74HC14│
        ─┬─    │ NOT         │     └──┬───┘
        GND        
                 (optional)

Schmitt trigger has HYSTERESIS:
├─ Switches HIGH at 3.5V
├─ Switches LOW at 1.5V
├─ 2V "dead zone" ignores noise
└─ Clean digital output ✓


Complete Reset Circuit:
───────────────────────

    VCC
     ├─ 10kΩ ─┬─ [DS1233] ──┬──► Power-On Reset
     │        │  Supervisor     │        │             │
     │        └─────────────┤
     │                      │   OR gate
┌─────────────┤   (74HC32)
     │        │             │
     ├─ 10kΩ ─┴─ Switch ────┴──► Final RESET
                                  (to all /CLR)
    GND

Features:
─────────
Automatic power-on reset
Manual button reset
Debounced
Noise immune
Reliable!


Distribution to Components:
────────────────────────────

    RESET ──┬──► PC (U6-U9 /CLR pins)
            ├──► (Other clearable components)
            └──► Control unit

For Hack:
─────────
PC needs reset (start at 0)
Registers don't need reset (A-inst loads them)
Keep it simple!

Single-Step and Debug Mode

Why Single-Step?

Problem: Computer Runs Too Fast!
─────────────────────────────────

At 8 MHz:
├─ 8 million instructions per second
├─ Impossible to see what's happening
├─ Can't debug effectively
└─ Like watching hummingbird wings!

Solution: Single-Step Mode
──────────────────────────
├─ Execute ONE instruction
├─ Then STOP
├─ Wait for manual trigger
├─ Then next instruction
└─ Human-speed debugging!

Use Cases:
──────────
1. Verify instruction execution
2. Watch register changes
3. Debug programs step-by-step
4. Educational demonstrations
5. Hardware troubleshooting

Single-Step Circuit

Basic Approach: Manual Clock
─────────────────────────────

Replace automatic clock with button:

    VCC
     ├─ 10 (pull-up)
     ├────────► CLOCK OUT
    ─┴─  Button
    ─┬─  (normally open)
    GND

Problem: Switch bounce!
Each press might trigger multiple clocks!
BAD! Multiple instructions execute!


Better: Debounced Single-Step
──────────────────────────────

Use 74HC74 edge-triggered flip-flop:

         VCC
          ├─ 10kΩ
          ├────┬─────► To D input
          │    │
         ─┴─  ┌┴┐
    Button    │ │ 100nF
         ─┬─  └┬┘
          │    │
         GND  GND
          └──────────► To CLK input


Circuit Diagram:
────────────────

                74HC74
          ┌───────────────┐
    VCC ──┤D          │               │
Button ───┤>CLK        Q  ├──► Single Clock Pulse
    │     │               │
   10kΩ   │           /Q  ├──┐
    │     │               │  │
   VCC/CLR├──┘
          └───────────────┘


How It Works:
─────────────

1. Button released:
   ├─ D = 1 (pulled high)
   ├─ CLK = 1 (pulled high)
   └─ Q = (previous state)

2. Button pressed:
   ├─ CLK goes LOW (falling edge)
   ├─ But 74HC74 triggers on RISING edge
   └─ Nothing happens yet

3. Button released:
   ├─ CLK goes HIGH (rising edge!)
   ├─ D is HIGH, so Q goes HIGH
   └─ One clean pulse!
4. /Q feeds back to /CLR:
   ├─ When Q goes HIGH, /Q goes LOW
   ├─ /CLR activates, clears flip-flop
   └─ Q returns LOW automatically

Result: One SHORT pulse per button press!
Perfect for single-stepping!

Timing Diagram:
───────────────

Button:   ──╗╔╗╔╗╔╗╔╗╔══════════╗╔╗══
Press ──►   ╚╝╚╝╚╝╚╝╚╝    ▲     ╚╝╚╝
Release
CLK:      ════════════════╗╔══════════
                          ╚╝
Rising edge
Q Output: ────────────────╗╚══════════
(pulse)                   ╚══╝
                          ◄──► ~50ns pulse

Computer executes ONE instruction!

Combined Fast/Slow Clock

Best Solution: Mode Switch
──────────────────────────

Combine automatic and manual clock:

         ┌─── 555 Timer (8 MHz)
    SW ──┼─── Single-Step Circuit
         └───► [MUX] ──► CLOCK OUT
         Mode Select


Using 74HC157 Multiplexer:
──────────────────────────

         555 Timer ────┐
A input
                    ┌──▼────┐
                    │74HC157│
         Manual ────┤  MUX  ├──► CLOCK OUT
     Single-Step    │       │
                    │       │
         MODE ──────┤SELECT        Switch      └───────┘
    ┌────┴────┐
RUNMODE = 0Select 555 (run)
STEPMODE = 1Select manual (step)
    └─────────┘


Complete Debug Circuit:
───────────────────────

     555 ─────────┐
     8MHz         │         ┌─────────┐
                  ├─────────┤A      Y ├──► CLOCK
     Manual ──────┤         │ 74HC157 │
     Step         └─────────┤B    MUX                            │         │
                  ┌─────────┤SELECT     Mode Switch ─┤         └─────────┘
     [RUN/STEP]     LED ─────────┴─────────► Visual indicator
     (indicates STEP mode)


Features:
─────────
Fast mode: 8 MHz automatic
Step mode: Manual single-step
Switch between modes instantly
LED shows current mode
Perfect for debugging!


Usage:
──────

Development:
├─ Set to STEP mode
├─ Load program
├─ Press button to execute each instruction
├─ Watch registers/memory change
├─ Verify program works
└─ Debug problems

Production:
├─ Set to RUN mode
├─ Full speed execution
├─ Normal operation
└─ Toggle to STEP for troubleshooting


Adding Speed Control:
─────────────────────

For intermediate speeds:

     555 ─────────┐
    (variable)                  ├─────────[MUX A]
     555 ─────────┤
    (fast 8MHz)                  ├─────────[MUX B]
     Manual ──────┤
     Step         └─────────[MUX C]

     Select ──────────────►[MUX]
     [FAST/VAR/STEP]

Three modes:
├─ FAST: 8 MHz (normal operation)
├─ VARIABLE: 1 Hz - 1 kHz (watch execution)
└─ STEP: Manual (single instruction)

Perfect for learning and debugging!

PCB Layout for Clock System

Clock Generation Area

Physical Layout:

┌─────────────────────────────────┐
Clock Generation (corner)│                                 │
│  ┌──────────────────────────┐  │
│  │ 555 Timer (U_CLK1)       │  │
│  │ - R1, R2, C1 close by    │  │
│  │ - Decoupling cap (0.1µF) │  │
│  └────────┬─────────────────┘  │
│           │                     │
│           │ 8MHz (before buffer)│           ▼                     │
│  ┌──────────────────────────┐  │
│  │ 74HC04 Buffer (U_CLK2)   │  │
│  │ - Two-stage buffering    │  │
│  │ - Decoupling cap         │  │
│  └────────┬─────────────────┘  │
│           │                     │
│           │ Buffered 8MHz       │
│           ▼                     │
│  ┌──────────────────────────┐  │
│  │ Mode Switch (optional)   │  │
│  │ - RUN/STEP selector      │  │
│  │ - 74HC157 MUX            │  │
│  └────────┬─────────────────┘  │
│           │                     │
│           │ FINAL CLOCK│           ▼                     │
To distribution            │
└─────────────────────────────────┘

Location: Corner of board
Size: ~3cm × 3cm
Critical: Short traces, clean power

Clock Distribution Traces

Star Topology Routing:

           Clock Source
              (U_CLK2)
       ┌─────────┼─────────┬─────────┐
       │         │         │         │
      60mm      60mm      60mm      60mm
       │         │         │         │
       ▼         ▼         ▼         ▼
    ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
A   │ │  D   │ │  PC  │ │Ctrl  │
Reg  │ │ Reg  │ │Counter│ Unit    └──────┘ └──────┘ └──────┘ └──────┘


Trace Requirements:
───────────────────

Width: 0.5mm (20 mil)
├─ Wider than data traces
├─ Lower resistance
└─ Better signal integrity

Length matching:
├─ All traces within ±5mm
├─ Minimizes skew
└─ <1ns timing variation

Impedance: ~50-75Ω
├─ Controlled impedance
├─ For high-speed designs
└─ Not critical at 8 MHz

Separation: 0.5mm minimum
├─ Away from other signals
├─ Reduces crosstalk
└─ Especially from data buses


Layer Assignment:
─────────────────

Top Layer (F.Cu):
├─ Clock source
├─ Star distribution traces
├─ Short, direct paths
└─ No vias if possible!

Bottom Layer (B.Cu):
├─ Ground plane UNDER clock traces
├─ Solid return path
├─ Critical for signal integrity!
└─ No gaps in plane


Example Layout (Top View):

    [CLK SOURCE]
         ├────────────────┐ (0.5mm trace)
         │                │
         │                │
    [Group 1]        [Group 2]
    A, D Regs        PC Counter
         │                │
         │                │
    [Group 3]        [Group 4]
    Control          Spare

Equal star pattern
Balanced loading
Clean routing ✓

Critical Design Rules

Rule 1: Keep Clock Traces SHORT
────────────────────────────────
├─ Maximum length: 10cm total
├─ Shorter is better
├─ Direct routing only
└─ Every mm counts!


Rule 2: Solid Ground Return
────────────────────────────
├─ Unbroken ground plane under clock
├─ Stitching vias every 10mm
├─ Clock return current path
└─ Essential for signal integrity!


Rule 3: Avoid Crosstalk
────────────────────────
├─ 0.5mm minimum spacing to data
├─ No parallel runs >10mm
├─ Cross at 90° if needed
└─ Clock is sensitive to noise!


Rule 4: Buffer Close to Source
───────────────────────────────
├─ 74HC04 within 20mm of 555
├─ Short connection
├─ Clean signal into buffer
└─ Then distribute from buffer


Rule 5: Decoupling at Every IC
───────────────────────────────

At 555:
├─ 0.1µF ceramic (close!)
├─ 10µF electrolytic (nearby)
└─ Stabilizes oscillation

At 74HC04:
├─ 0.1µF ceramic
└─ Within 5mm of VCC pin

At every clock destination:
├─ 0.1µF ceramic at each IC
├─ Prevents ground bounce
└─ Critical when switching!


Rule 6: Test Points
────────────────────
├─ Add test point at clock source
├─ Add test point after buffer
├─ Add test point at each destination
└─ Easy debugging with scope!


Visual Representation:
──────────────────────

TOP VIEW:
┌─────────────────────────────────┐
│                                 │
│  ●──────────────────┐           │
CLK                │           │
Source             │           │
│                     │           │
│              ═══════╪═══════     (Ground plane)
│                     │           │
│         ┌───────────┼──────┐    │
│         │           │      │    │
│         ▼           ▼      ▼    │
[IC1]       [IC2]  [IC3]│       │           │      │      │
0.1µF       0.1µF  0.1µF    (Decoupling)
│       │           │      │      │
GND         GND    GND└─────────────────────────────────┘

SIDE VIEW:
           Top Layer
         ──────┬──────  (Clock trace)
                (via if needed)
       ════════════════  (Ground plane)
           Bottom Layer

Clock has direct ground return path!

Complete Timing Analysis

Worst-Case Timing

Complete Clock Cycle Breakdown (125ns):

Phase 1: Clock Edge (t=0ns)
───────────────────────────
Event: Rising edge of clock
Action: All flip-flops sample inputs


Phase 2: Clock-to-Output (0-25ns)
──────────────────────────────────
Event: Register outputs change
Delay: 25ns (74HC574 t_co)

Registers affected:
├─ A Register: A_Out[15:0] updates
├─ D Register: D_Out[15:0] updates
└─ PC: PC_Out[14:0] updates


Phase 3: Combinational Logic (25-100ns)
────────────────────────────────────────

Path 3a: ROM Access (if instruction fetch)
───────────────────────────────────────────
t=25ns:  PC_Out stable
t=95ns:  ROM data valid (70ns access)

Path 3b: ALU Operation
──────────────────────
t=25ns:  Register outputs stable
t=37ns:  Through input multiplexers
t=52ns:  Through input conditioning
t=92ns:  Through ALU core (carry chain)
t=102ns: Through output stage

Path 3c: Memory Access (if data access)
────────────────────────────────────────
t=25ns:  A_Out stable (address)
t=80ns:  RAM data valid (55ns access)
t=85ns:  Through transceiver
t=97ns:  Through X input mux


Phase 4: Setup Time (100-112ns)
────────────────────────────────
Event: Data stabilizes at register inputs
Requirement: Must be stable 12ns before clock

Latest data arrival: 102ns (ALU output)
Setup requirement: 112ns (125ns - 12ns - 1ns margin)
Margin: 10ns ✓


Phase 5: Clock Edge (t=125ns)
──────────────────────────────
Event: Next rising edge
Action: Capture new data
Result: Cycle repeats


Critical Path Summary:
──────────────────────
RegisterALURegister
25ns + 77ns + 12ns + 11ns margin = 125ns

This is the bottleneck!
Maximum frequency: 8 MHz

Timing Diagram:
───────────────

Time:    0    25   50   75   100  125  (ns)
         │    │    │    │    │    │

CLK:     ───╗     ╔════╗     ╔════
            ╚═════╝    ╚═════╝
            ▲              ▲
        Capture        Capture

REG_OUT: ══════╱╲╱╲╲═══════════════
              └──►│◄─ Valid
                 25ns

ALU_IN:  ═════════╱╲╲════════════════
                 └─►│ Valid
                   37ns

ALU_OUT: ════════════════╱╲╲═════════
                        └─►│ Valid
                         102ns

REG_IN:  ════════════════════╱╲══════
(setup)                     └►│ ◄12ns
                            112ns

All timing met!

Timing Margins

Timing Budget Analysis:
───────────────────────

Total period available: 125ns
Setup time required: 12ns
Hold time required: 3ns
Clock uncertainty: 5ns (jitter, skew)

Available for logic: 125 - 12 - 5 = 108ns


Actual usage:
─────────────
Register output: 25ns
Mux + conditioning: 12ns + 15ns = 27ns
ALU core: 40ns
Output processing: 10ns
Total: 102ns

Margin: 108ns - 102ns = 6ns
Percentage: 6/125 = 4.8%

This is TIGHT!

Where Margins Went:
───────────────────

Design target: 125ns (8 MHz)
Critical path: 102ns
Setup time: 12ns
Margin: 11ns (8.8%)

Consumed by:
├─ PCB trace delays: 2ns
├─ Clock buffer delays: 3ns
├─ Process variation: 3ns
├─ Temperature effects: 2ns
├─ Voltage variation: 1ns
└─ Final margin: 0ns

Barely makes it!
This is why we chose 8 MHz not 10 MHz!


Safety Factors:
───────────────

Component aging:
├─ Gates slow down over years
├─ ~5% degradation over 10 years
└─ Need margin for longevity

Temperature:
├─ IC speed varies with temperature
├─ Typical: -40°C to +85°C range
├─ Slower at high temperatures
└─ Need margin for hot operation

Voltage:
├─ 5V ±5% = 4.75V to 5.25V
├─ Slower at low voltage
└─ Need margin for low VCC

Process variation:
├─ ICs from different batches vary
├─ Some faster, some slower
└─ Design for worst-case IC


Derating Factors Applied:
──────────────────────────

Nominal timing: 102ns
Temperature derating: 1.05× → 107ns
Voltage derating: 1.03× → 110ns
Aging derating: 1.02× → 112ns
Process variation: 1.05× → 118ns

Final worst-case: 118ns
Required: 108ns with 5ns uncertainty
Total needed: 123ns

Clock period: 125ns
Margin: 2ns (1.6%)
VERY tight, but should work!


To Increase Margin:
────────────────────

Option 1: Slower clock
├─ Use 7 MHz (143ns period)
├─ Margin increases to 25ns (17%)
└─ Much safer!
Option 2: Faster parts
├─ Use 74AC instead of 74HC
├─ Gain ~25ns (faster gates)
└─ Expensive, harder to find

Option 3: Optimize critical path
├─ Use carry-lookahead in ALU
├─ Gain ~20ns
└─ More complex design

Recommendation: 8 MHz is fine!
But have 7 MHz backup if problems arise.

Advanced: Clock Domains

Single Clock Domain (Our Design)

The Hack computer uses ONE clock:

         ┌─────────┐
CLOCK8 MHz
         └────┬────┘
    ┌─────────┼─────────┬─────────┐
    │         │         │         │
    ▼         ▼         ▼         ▼
 [A Reg]  [D Reg]    [PC]     [Control]

ALL components use SAME clock
├─ Same frequency (8 MHz)
├─ Same edges (all synchronized)
├─ No clock domain crossing
└─ SIMPLE!

Benefits:
─────────
No metastability between domains
Simple timing analysis
Predictable behavior
Easy to debug
Recommended for beginners!


When This Works:
─────────────────
├─ All components on same board
├─ Similar speeds required
├─ No external interfaces
└─ Educational/hobby projects

Perfect for Hack!

Multiple Clock Domains (Advanced)

When You Need Multiple Clocks:
───────────────────────────────

Example: Add Serial Port
─────────────────────────

    ┌─────────┐              ┌─────────┐
System8 MHzSerial115.2 kHz
Clock   │              │ Clock    └────┬────┘              └────┬────┘
         │                        │
         ▼                        ▼
    ┌─────────┐              ┌─────────┐
CPU    │              │ UARTDomain  │◄───Data────►│ Domain    └─────────┘              └─────────┘
                             
                Crossing boundary!


Problem: Clock Domain Crossing (CDC)
─────────────────────────────────────

When data crosses from one domain to another:
├─ Source clock: 8 MHz
├─ Destination clock: 115.2 kHz
├─ Clocks are ASYNCHRONOUS (unrelated)
├─ Setup/hold times can be violated
└─ METASTABILITY risk!

Solution 1: Two-Stage Synchronizer
───────────────────────────────────

Always use when crossing domains:

    Domain A (8MHz)         Domain B (115.2kHz)
         │                       │
    Data │                       │ CLK_B
     │   │   ┌────┐   ┌────┐    │
     └───┼──►│ FF │──►│ FF │────┼──► Sync Data
         │   │    │   │    │    │
         └───┤>CLK│   ├>CLK├────┘
             └────┘   └────┘

First FF: Might go metastable
Second FF: Samples stable output
Latency: 2 cycles of slower clock


Solution 2: Handshake Protocol
───────────────────────────────

For bidirectional communication:

    Domain A              Domain B
         │                    │
    REQ ─┼─────────────────►┼─► (synchronized)
         │                    │
         │◄────────────────┼─── ACK (synchronized)
         │                    │
    DATA ┼─────────────────►┼─► (stable during handshake)

Steps:
1. A asserts REQ
2. B sees REQ (after sync delay)
3. B captures DATA
4. B asserts ACK
5. A sees ACK (after sync delay)
6. A deasserts REQ
7. B deasserts ACK
8. Done! Ready for next transfer

Slow but reliable!


Solution 3: Async FIFO
──────────────────────

For high-throughput data:

         Write Side          Read Side
         (Domain A)         (Domain B)
              │                  │
         ┌────▼─────────────┬────▼────┐
WriteReadPointerPointer         │        │         │    │    │
         │        ▼         │    ▼    │
         │    ┌──────────┐  │         │
         │    │  Memory  │  │         │
         │    │  Array   │  │         │
         │    └──────────┘  │         │
         │                  │         │
         └──────────────────┴─────────┘

Complex but allows continuous data flow!


When Not to Use Multiple Clocks:
─────────────────────────────────
Simple systems (use one clock!)
Beginner projects
When not required
Educational purposes

Stick with single clock domain!

Testing and Debugging Clock

Verification with Oscilloscope

Essential Measurements:
───────────────────────

Test 1: Frequency
─────────────────
Connect scope to clock output
Measure period between edges

Target: 125ns (8 MHz)
Tolerance: ±5% (119-131ns)
Method: Use scope's frequency measurement


Test 2: Duty Cycle
───────────────────
Measure HIGH time vs total period

Target: 50% (62.5ns HIGH, 62.5ns LOW)
Actual 555: ~69% (acceptable)
Method: Cursors to measure HIGH time


Test 3: Rise/Fall Time
───────────────────────
Measure 10% to 90% transition

         4.5V ──────────────
             ╱  ◄── Measure this
         0.5V ────────────

Target: <10ns
Good 74HC04: 5-8ns
Method: Zoom in on edge, use cursors


Test 4: Voltage Levels
──────────────────────
HIGH level: Should be 4.5-5.0V
LOW level: Should be 0-0.5V

Anything in between = problem!


Test 5: Jitter
──────────────
Trigger on edge, watch over time

Persistence mode on scope:
├─ Good: Tight band (1-2ns)
├─ Bad: Fuzzy band (>5ns)
└─ If bad: check power, filtering


Test 6: Clock at Each Destination
──────────────────────────────────
Probe clock at:
├─ A Register CLK pin
├─ D Register CLK pin
├─ PC CLK pin
└─ Should all look identical!

If different:
Bad connections
Excessive loading
Poor PCB routing

Logic Analyzer Verification

Using Logic Analyzer:
─────────────────────

Connect multiple channels:
├─ Ch 1: Clock signal
├─ Ch 2: LOAD_A signal
├─ Ch 3: LOAD_D signal
├─ Ch 4: WRITE_M signal
├─ Ch 5-20: Data bus bits
└─ Ch 21-24: Address bus bits


Analyze Timing Relationships:
──────────────────────────────

View 1: Clock vs Control Signals
─────────────────────────────────

CLK:     ───╗     ╔════╗     ╔════
            ╚═════╝    ╚═════╝

LOAD_D:  ───────────────╗   ╔═════
                        ╚═══╝

Verify:
LOAD_D pulses AFTER clock edge
Duration matches clock HIGH time
Setup time before next edge


View 2: Complete Instruction
─────────────────────────────

Trigger on PC change
Capture full instruction cycle:

PC:      ──── 0x0100 ──────── 0x0101
INST:    ──── 0xEC10 ───────────────
LOAD_D:  ───────────╗  ╔════════════
DATA:    ──── 0x0005 ─┴─ 0x0006 ────
D_OUT:   ──── 0x0005 ───── 0x0006 ──

Analysis:
PC increments one cycle later
Instruction decoded correctly
Data updates on clock edge
Everything synchronized!


View 3: Memory Access
─────────────────────

A_OUT:   ──── 0x0100 ─────────────
READ_M:  ───────────╗  ╔══════════
         ───────────╚══╝
M_DATA:  ═══════════╱╲╲═══════════
                   └─►│ Valid
                     70ns

Verify:
Address stable before READ_M
Data valid before clock edge
Timing margins met

Common Clock Problems

Problem 1: No Clock Signal
──────────────────────────

Symptoms:
├─ Nothing works
├─ All outputs frozen
└─ No activity anywhere

Debug:
1. Check 555 power (VCC, GND)
2. Check 555 output with scope
3. Check buffer IC (74HC04)
4. Check for shorts
5. Verify component values (R, C)


Problem 2: Wrong Frequency
──────────────────────────

Symptoms:
├─ Clock too fast/slow
├─ Incorrect period measured
└─ System timing errors

Debug:
1. Measure actual frequency
2. Check R1, R2, C1 values
3. Calculate expected frequency
4. Replace suspect components
5. Use potentiometer for adjustment


Problem 3: Clock Not Reaching ICs
──────────────────────────────────

Symptoms:
├─ Some ICs work, some don't
├─ Inconsistent behavior
└─ Random errors

Debug:
1. Probe clock at each IC
2. Check for broken traces
3. Check buffer drive strength
4. Measure capacitive loading
5. Add additional buffers if needed


Problem 4: Slow Edges
──────────────────────

Symptoms:
├─ Rise time >10ns
├─ Glitches or double-triggering
└─ Timing errors at high speed

Debug:
1. Measure rise/fall time
2. Check capacitive loading
3. Shorten clock traces
4. Add stronger buffer
5. Check for poor connections


Problem 5: Jitter/Instability
──────────────────────────────

Symptoms:
├─ Edges wobble
├─ Random timing errors
└─ Occasional glitches

Debug:
1. Check power supply (ripple?)
2. Add decoupling capacitors
3. Check 555 components
4. Look for noise sources nearby
5. Improve ground plane


Problem 6: Reset Issues
───────────────────────

Symptoms:
├─ PC doesn't start at 0
├─ Random startup state
└─ Unreliable reset

Debug:
1. Check reset circuit
2. Measure reset duration
3. Verify reset reaches all ICs
4. Check for bounce
5. Add reset supervisor IC

Summary: The Clock Philosophy

The Clock is the HEARTBEAT:
───────────────────────────

Just as your heart:
├─ Beats regularly
├─ Coordinates blood flow
├─ Keeps body synchronized
└─ Life depends on it!

The clock:
├─ Ticks regularly
├─ Coordinates data flow
├─ Keeps computer synchronized
└─ Operation depends on it!


Key Principles:
───────────────

1. Synchronization
──────────────────
Everything happens on clock edges
No chaos, perfect coordination


2. Timing Margins
─────────────────
Setup and hold times MUST be met
Margins protect against variation


3. Signal Quality
─────────────────
Clean edges, stable frequency
Jitter and noise are enemies


4. Distribution
───────────────
Star topology, equal lengths
Every component gets clean clock


5. Simplicity
─────────────
Single clock domain preferred
Avoid complexity when possible


The Beauty:
───────────

One simple signal (clock):
├─ Organizes everything
├─ Enables sequential logic
├─ Makes timing predictable
├─ Allows complex behavior
└─ Elegant simplicity!
With clock: Working computer! 🎉
Without clock: Pile of silicon!

The clock is complete! Would you like me to explain:

  1. How all the major systems integrate together?
  2. Building and testing the complete Hack computer?
  3. Writing and running programs on the finished computer?
  4. How modern CPUs handle clocking (PLLs, clock trees)?