# Tactiverge Academy — companion code for "Sequential logic: latches, flip-flops and clocks"
# Lesson: https://tactiverge.win/academy/embedded-systems/digital-electronics-fundamentals/sequential-logic-and-clocks/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
def next_state(q):
    """Next-state logic for a 3-bit counter: the D inputs of three flip-flops."""
    q0, q1, q2 = q
    d0 = 1 - q0
    d1 = q1 ^ q0
    d2 = q2 ^ (q1 & q0)
    return (d0, d1, d2)

q = (0, 0, 0)                         # the flip-flops start cleared
for edge in range(10):
    value = q[0] + 2 * q[1] + 4 * q[2]
    print(f"after {edge} clock edges: Q2 Q1 Q0 = {q[2]}{q[1]}{q[0]}  ({value})")
    q = next_state(q)                 # every flip-flop updates on the same edge
