Tricky Circuit · Local article preview

Two Clock Inputs Make an Up/Down Counter Protocol

A counter that goes up and down needs more than two buttons. With the TI SN74HC193N, the clock you are not pulsing must stay HIGH. Load fourteen, count up to fifteen and zero, then count down to fifteen and fourteen. Watch a terminal signal become active during the LOW half before the wraparound edge.

A binary counter stores a whole number as bits, each a logic 0 or 1. Here LOW means logic 0 and HIGH means logic 1. A clock is a control signal whose transition requests a change; a rising edge goes from LOW to HIGH. This four-bit counter has sixteen states,0–15. Modulo16 means that one step above15 returns to 0 and one below 0 returns to 15. Carry and borrow are terminal-count signals for upward and downward counting; their LOW conditions also depend on the selected clock. Its parallel load replaces all four bits from four separate data inputs. Asynchronous clear and load act without a clock edge. Active LOW means a function is asserted by LOW; the suffix _N marks that polarity.

This is a source-qualified design and a complete offline exercise, not a built or measured circuit. The Python model describes ideal settled logic. The optional Pico controller has not been executed or built on a target. No count, edge speed, timing margin or waveform in this article is presented as a bench result. Use the host-only route first; operate hardware only after the qualification procedure below.

What each named part does

An integrated circuit (IC) combines electronic functions in one package. U1 is specifically Texas Instruments SN74HC193N, the 16-pin plastic dual-inline package (PDIP), top view with its orientation notch upward. It is the HC binary dual-clock device, not SN74LS193, HC191 or a decimal counter. CMOS means complementary metal–oxide–semiconductor; HC is TI's high-speed CMOS family. U2/U3 are specifically SN74AHCT125N,14-pin PDIP non-inverting buffers: an enabled buffer copies HIGH as HIGH and LOW as LOW. The AHCT family uses CMOS circuitry with input thresholds compatible with transistor–transistor logic (TTL); here that lets a documented3.3 V command drive a 5 V logic output. An output enable, OE_N, passes the signal when LOW; HIGH would disconnect it into a high-impedance state. All eight channels are used and always enabled in this fixture.

The original Raspberry Pi Pico with RP2040 supplies eight general-purpose input/output (GPIO) commands. Its3.3 V logic cannot be assumed to meet5 V HC thresholds directly. It receives no 5 V signal. Pico power comes only from Universal Serial Bus (USB). Direct current (DC) describes the steady rail and held voltage readings. A digital multimeter (DMM) measures the rail; an oscilloscope displays voltage against time and is needed to qualify edges. A volt (V) is voltage; an ampere (A) is current, with a milliampere (mA) one-thousandth and a microampere (µA) one-millionth of it. An ohm (Ω) is resistance; a kilohm (kΩ) is 1000 Ω. A farad is capacitance; a nanofarad (nF) is one-billionth of a farad. A nanosecond (ns) is one-billionth of a second. A watt (W) is a unit of power. A light-emitting diode (LED) is an indicator that would add an electrical load; none is used here.

ItemSpecified part or settingPurpose
U11× TI SN74HC193NStores/counts four bits; exposes carry/borrow outputs.
U2/U32× TI SN74AHCT125NEight non-inverting3.3 V-to-5 V command channels.
R1–R88 × 10 kΩ,1%, at least0.25 WHold each AHCT input LOW while Pico is unpowered or initializing. No resistor pulls an HC input/output down.
C1–C33 × 100 nF ceramic, X7R,10%, rated at least16 VLocal supply bypass, one beside each IC power pair; X7R is a ceramic temperature-characteristic designation, not a precision charge standard.
CommandsOriginal RP2040 Pico, MicroPython1.26.0Separate manual steps, not a timing instrument or 5 V receiver.
Logic supplyIsolated regulated 5.0 V bench output; configure40 mA; verify4.9–5.1 V at all ICsShared V5, the named 5 V logic rail, for all three chips; no independent buffer/counter power switch. Current setting is not a guaranteed damage-prevention mechanism.
ObservationRIGOL DHO804; PVP2150 probes set 10X, compensated; scope channels set 1 MΩ and matching10X factorHigh-resistance analog observation. Never select50 Ω termination or attach an indicator load.
Steady rail checkKeysight34461 A, fixed10 V DC range,10 MΩ input modeRail check only; a slow DMM reading does not qualify an edge.

Connect the complete fixture with power OFF

First prepare the DHO804 correctly. Power it only with its supplied15 V,3 A adapter. Its Type-C power lead does not provide protective earth (PE), the equipment safety-ground connection: connect the supplied grounding lead from its rear ground terminal to a suitable protective-earth point before any input/output connection. Keep it connected. This is not a floating measurement. Then connect every probe ground clip to G0. G0 is the circuit's common return, not an instruction to guess a protective-earth point from a bench-supply post. The DHO800 user guide §1.1 and§4.3.2 govern this installation.

The drawing uses matching named net flags: the two ends bearing the same name are the same wire. G0 symbols are all the same net. Numbers beside IC terminals are exact package pins, not row numbers on a breadboard. Use short connections, inspect split breadboard power rails, and check continuity while both supplies are OFF. All eight input resistors go to G0 on the Pico/AHCT-input side. There are no pull resistors on buffered outputs. No HC output connects to the Pico, even briefly.

Two SN74AHCT125N banks buffer eight Pico commands into exact SN74HC193N inputs. Every buffer enable is grounded, eight input-side10k resistors and three supply bypasses are shown. Six HC outputs terminate at named observation points.
Functional low-voltage signal wiring. Adapter/rear protective-earth installation is mandatory above and is not depicted here. Matching names connect the buffer-bank flags to U1; all G0 symbols share one return. Editable Scalable Vector Graphics (SVG) and full-size Portable Network Graphics (PNG) are included.
CommandPico GPIO / physical pinAHCT input→outputHC193 destination
A(bit0)GP2 /4U2:2→3U1:15
B(bit1)GP3 /5U2:5→6U1:1
C(bit2)GP4 /6U2:9→8U1:10
D(bit3)GP5 /7U2:12→11U1:9
UPGP6 /9U3:2→3U1:5
DOWNGP7 /10U3:5→6U1:4
CLRGP8 /11U3:9→8U1:14
LOAD_NGP9 /12U3:12→11U1:11

VCC names the positive supply pin and GND names its return. U1 pin 16→V5 and pin 8→G0; U2/U3 pin 14→V5 and pin 7→G0. On each buffer connect enable pins 1,4,10,13 directly to G0. No spare AHCT input is left floating: all eight signal inputs are used. C1 is U1 pin 16-to 8; C2/C3 are their respective buffer pin 14-to 7, physically beside those pairs. Connect supply negative and Pico GND physical pin 3 to G0. Do not connect V5 to Pico 3V3, VBUS or VSYS. Keep other supply channels and tracking modes off; the Pico uses its own USB power.

U1 outputs are QA pin 3, QB pin 2, QC pin 6, QD pin 7, carry CO_N pin 12 and borrow BO_N pin 13. They are driven outputs, never connected together or to a supply. Leave them open except for the qualified high-resistance probes. No LED, bus receiver, resistor ladder or second counter is attached in this experiment.

Prove the interface before trusting a count

The HC193 recommended supply range is 2–6 V; the AHCT125 recommended range is 4.5–5.5 V. Their intersection permits the chosen shared 4.9–5.1 V fixture rail. Work at an ordinary 18–28°C bench temperature, a deliberately narrow range inside both SN74 data-sheet ranges. Absolute-maximum ratings are damage boundaries, not operating targets. Check the actual rail at all three chips under both LOW and HIGH command states; a current-limit setting does not certify voltage, loading or protection.

At the RP2040's tabulated 3.3 V input/output (I/O)-supply condition, its minimum HIGH output is 2.62 V and maximum LOW is 0.5 V at the selected drive current. AHCT requires at least2.0 V for HIGH and no more than 0.8 V for LOW. The corresponding listed margins are0.62 V and0.30 V. Set each GPIO pad (the chip’s I/O connection) to 4 mA drive with fast slew (the faster output-transition setting). With a conservative3.4 V pull-resistor calculation, each10kΩ1% pull draws at most3.4/9900≈0.343 mA; adding1 µA AHCT leakage gives less than 0.345 mA. Eight such loads total less than 2.76 mA, not eight times the 4 mA drive setting. These are static loading checks at stated conditions, not a measured Pico waveform.

The AHCT output's4.4 V minimum HIGH/0.1 V maximum LOW values apply at its light50 µA load condition and4.5 V supply test point. Its8 mA HIGH value is only 3.8 V; that row cannot justify the same margin. Each output here drives one HC input(≤1 µA leakage) and at most two measurement paths each at least1 MΩ. Even the pessimistic5.1 V screen is 1 µA+2 × 5.1 V/1 MΩ=11.2 µA, below 50 µA. The named 10X probe and DMM have much higher nominal resistance. Do not add10 kΩ output pulls: they would break this load argument. Capacitance and wiring still affect edges.

HC193's listed HIGH requirements are3.15 V at 4.5 V supply and4.2 V at 6 V; listed LOW limits are1.35 V and1.8 V respectively. Use the stricter4.2 V HIGH and1.35 V LOW as this fixture's acceptance screen across the narrow4.9–5.1 V rail, with actual input voltages staying between G0 and local V5. This is a conservative design screen using listed endpoints, not a new TI threshold specification at 5.0 V. The light-load AHCT table suggests0.2 V HIGH margin against that screen; verify real pin voltages and uncertainty instead of claiming an interpolated guarantee.

Every AHCT signal input must also meet its maximum20 ns/V transition rate. Every HC input—A, B, C, D, UP, DOWN, CLR and LOAD_N—must have a clean single crossing, correct levels and rise/fall times no more than 400 ns, the stricter HC table endpoint. A transition time measures the analog ramp, not the delay between Python commands. Use compensated probes with short ground connections; include probe error, bandwidth and actual capacitive loading. A fast-slew register setting alone certifies none of these. If a channel rings across the threshold repeatedly, overshoots a rail or cannot be resolved by the instrument, stop and correct the fixture; mark its gate unqualified.

For a deliberately slow protocol, also require actual HIGH/LOW clock halves and asserted clear/load pulses at least150 ns; data stable at least140 ns before LOAD_N rises and5 ns after; and clear/load inactive at least140 ns before a count edge. These chosen limits cover the most demanding SN74HC193 timing-table entries, including its low-supply rows, rather than borrowing25°C typical speed. Both clocks remain HIGH through control release. The controller's200 ms observation pauses are convenient pacing only: they cannot prove analog slew, pulse integrity, setup or hold time. Setup is the required stable interval before the relevant edge; hold is the stable interval after it. Record actual bounds in the blank qualification sheet. Any failed or missing item means no physical comparison is qualified.

Clear, load, then change direction

Power sequence: with the shared external5 V rail OFF, start the optional adapter manually. Its eight outputs initialize LOW; the input-side pulls also hold disconnected/unpowered commands LOW. With no Pico HIGH drive while5 V is OFF, this avoids relying on undocumented output power-off isolation. AHCT's input-leakage table includes VCC=0, but that is not proof the whole board cannot back-power. Enable the one shared rail only after the prompt, then assert CLR as the first commanded change. Power-up alone is not state evidence.

  1. Assert CLR HIGH. It overrides load, data and clocks and forces QA–QD LOW. While CLR remains HIGH, raise UP, then DOWN, then LOAD_N to HIGH, one command each. Release CLR to LOW only after the clocks and inactive load have settled. Count is now explicitly established as 0.
  2. Prepare14 without counting. Leave A LOW; set B, C, D HIGH one at a time while LOAD_N and both clocks remain HIGH. The binary word D C B A is 1110:8+4+2=14. Data changes alone do not change the stored count.
  3. Load. Assert LOAD_N LOW. Outputs follow the parallel data asynchronously, independently of clock pulses, unless CLR is HIGH. Release LOAD_N HIGH with data unchanged; wait through the actual setup/hold/control-recovery guards. Count remains14.
  4. Up to 15. Keep DOWN HIGH. Drive UP LOW and inspect the held state; carry is inactive. Raise UP: count becomes15. Carry is still HIGH while UP is HIGH.
  5. Wrap to 0. Lower UP again. Count is still15 and CO_N now becomes LOW. Raise UP: count becomes0 and CO_N returns HIGH. The LOW carry interval preceded the count edge; it is not a stored overflow bit.
  6. Reverse. Keep UP HIGH. Lower DOWN while count is 0: BO_N becomes LOW. Raise DOWN: count becomes15 and BO_N returns HIGH. A second DOWN LOW/HIGH pair reaches14. The other clock never goes LOW during either directional pulse.
  7. Finish. Record the last held observation before cleanup. Cleanup first asserts LOAD_N LOW to inhibit counting, then lowers CLR, data and both clocks. Its transient loaded values are not observations. Turn external5 V OFF next, then unplug Pico USB. Rewire only with both OFF. A crash/reset/disconnection is a new unqualified run: power OFF, inspect and restart through explicit clear.

Do not pulse both clocks, change direction with the other clock LOW, release clear/load near a clock edge, or substitute slow/bouncing manual buttons. The datasheet does not authorize arbitrary simultaneous clock/control transitions. The model refuses multi-input command jumps rather than fabricating an intermediate count. Even valid synchronous counting does not make every physical output transition perfectly simultaneous; wait for measured settling before decoding a held word.

Constructed settled-state timing sequence: clear,load14,up15 and0,down15 and14. Carry LOW occurs on the second UP LOW half; borrow LOW on the first DOWN LOW half. Columns are command indices,not measured time.
Generated from the delivered ideal model. Each column is one command, not an equal measured duration. Propagation delay means an input change takes time to reach an output; that delay, overshoot and metastability—an unresolved intermediate storage state—are deliberately absent here. The initial borrow indication is also a combinational model result under forced clear with DOWN LOW, not a startup/cascade recommendation. Editable SVG.

Record observations without inventing channels

Begin with one complete run using four scope channels at QA, QB, QC, QD; all probe grounds go to G0. Decode a settled word as QA+2QB+4QC+8QD. A separate repeated run can observe UP, DOWN, CO_N, BO_N together. Four channels cannot capture all six simultaneously. Record each run and its qualification separately; do not combine unrelated transient captures into one simultaneous six-signal measurement. For held states, sequential probe repositioning is allowed only after both supplies are OFF and the entire clear/load protocol is rerun; identify those as separate trials.

The physical sheet uses comma-separated values (CSV), a plain-text table. It contains all eighteen commanded states but no observations. kind=measured describes the intended transcription, not evidence already collected; every qualified starts no. Enter an observed count only from a qualified four-Q held/simultaneous observation; enter just a carry or borrow field from its separate qualified run and leave unavailable fields blank. Duplicate the template under a new run name instead of merging captures. Never copy predictions into observation fields. Attach instrument settings, source readings, record IDs, uncertainties and any refusal reason to the separate qualification sheet.

qualified=yes is your explicit assertion that every relevant worksheet condition passed for that run, wiring and load; the software cannot verify it. An unqualified physical entry remains visible but its comparison is withheld. An empty entry is not_observed, never a pass. Constructed rows reject observations outright. The program emits JavaScript Object Notation (JSON), a structured text result, only after the whole CSV validates; malformed or incomplete data give exit2 and no partial result.

Run the complete offline exercise

Use CPython3.9 or later on a computer. Save the supplied directory layout, or extract the complete reader ZIP archive. ZIP is a compressed file container. No extra Python package is required for the model/tests. The example is explicitly constructed; it provides no evidence that a Pico, buffer or counter was run.

python3 code/hc193_protocol.py constructed-example.csv
python3 -m unittest discover -s tests -v
# Optional qualified physical transcription; all blanks initially remain unobserved:
python3 code/hc193_protocol.py physical-blank.csv

The table below is a compact prediction check for normal counting, with CLR LOW and LOAD_N HIGH. It states settled logic only; use the full sequence to establish the initial count.

BeforeCommand / other clockAfterTerminal result
14UP LOW / DOWN HIGH14CO_N HIGH
14UP rises / DOWN HIGH15CO_N HIGH
15UP LOW / DOWN HIGH15CO_N LOW
15UP rises / DOWN HIGH0CO_N HIGH
0DOWN LOW / UP HIGH0BO_N LOW
0DOWN rises / UP HIGH15BO_N HIGH

Complete ideal protocol and CSV checker

Save as code/hc193_protocol.py. The initial count is unknown unless clear/load determines it. Each later row must change at most one input, so skipped intermediate commands are refused. That policy is stricter than the IC's full possible use; it is the declared fixture protocol, not a claim all rejected electrical histories have the same outcome.

"""Ideal steady-state SN74HC193 protocol, not an electrical simulator."""
import csv
import json
import sys

INPUTS = ("a", "b", "c", "d", "up", "down", "clr", "load_n")
FIELDS = ("step", "kind", "qualified") + INPUTS + (
    "observed_count", "observed_carry_n", "observed_borrow_n")


class Counter:
    def __init__(self):
        self.q = None
        self.previous = None

    def step(self, inputs):
        x = dict(inputs)
        if set(x) != set(INPUTS) or any(type(v) is not int or v not in (0, 1) for v in x.values()):
            raise ValueError("exactly eight binary integer inputs required")
        old = self.previous
        changed = [] if old is None else [k for k in INPUTS if x[k] != old[k]]
        # The fixture intentionally changes ONE signal per recorded command.
        # Missing intermediate commands are not reconstructed from snapshots.
        if len(changed) > 1:
            raise ValueError("multiple changed inputs: record every separate command")
        data = sum(x[k] << i for i, k in enumerate("abcd"))
        q = self.q
        if x["clr"]:
            q = 0
        elif not x["load_n"]:
            q = data
        elif old is not None:
            for name, other, delta in (("up", "down", 1), ("down", "up", -1)):
                if name in changed:
                    if x[other] != 1:
                        raise ValueError("other count clock must remain HIGH")
                    if old[name] == 0 and x[name] == 1:
                        if q is None:
                            raise ValueError("clear or load before counting")
                        q = (q + delta) % 16
        # Commit only after the complete event has passed validation.
        self.q, self.previous = q, x
        return {"count": q,
                "carry_n": None if q is None else int(not(q == 15 and x["up"] == 0)),
                "borrow_n": None if q is None else int(not(q == 0 and x["down"] == 0))}


def integer(text, lo, hi, name):
    if not isinstance(text, str) or not text.isascii() or not text.isdecimal():
        raise ValueError(name + ": unsigned decimal integer required")
    value = int(text)
    if not lo <= value <= hi:
        raise ValueError(name + ": out of range")
    return value


def analyze(rows):
    model, result = Counter(), []
    for index, row in enumerate(rows):
        if set(row) != set(FIELDS) or None in row or any(v is None for v in row.values()):
            raise ValueError("wrong CSV columns or missing/extra cell")
        if integer(row["step"], 0, 1000000, "step") != index:
            raise ValueError("steps must start at zero and increase by one")
        if row["kind"] not in ("constructed", "measured") or row["qualified"] not in ("yes", "no"):
            raise ValueError("kind or qualified invalid")
        x = {k: integer(row[k], 0, 1, k) for k in INPUTS}
        predicted = model.step(x)
        observed = {}
        for name, maximum in (("count", 15), ("carry_n", 1), ("borrow_n", 1)):
            value = row["observed_" + name]
            if value != "":
                observed[name] = integer(value, 0, maximum, name)
        if row["kind"] == "constructed" and observed:
            raise ValueError("constructed rows cannot contain physical observations")
        comparison = "not_observed"
        if observed:
            if row["qualified"] != "yes":
                comparison = "withheld_unqualified"
            elif any(predicted[k] is None for k in observed):
                comparison = "withheld_unknown_model"
            else:
                comparison = "match" if all(predicted[k] == v for k, v in observed.items()) else "mismatch"
        result.append({"step": index, "kind": row["kind"], "qualified": row["qualified"],
                       **{"expected_" + k: v for k, v in predicted.items()},
                       "observed": observed, "comparison": comparison})
    if not result:
        raise ValueError("no data rows")
    return result


def main(argv):
    if len(argv) != 2:
        print("usage: python3 hc193_protocol.py INPUT.csv", file=sys.stderr)
        return 2
    try:
        with open(argv[1], newline="", encoding="utf-8-sig") as stream:
            reader = csv.DictReader(stream, strict=True)
            if reader.fieldnames != list(FIELDS):
                raise ValueError("CSV header must match the supplied template exactly")
            result = analyze(reader)
        # Complete validation before emitting anything: late errors give no partial JSON.
        output = json.dumps({"scope": "ideal protocol; electrical qualification supplied by user",
                             "rows": result}, indent=2, allow_nan=False)
    except (OSError, UnicodeError, csv.Error, ValueError) as exc:
        print("refused: " + str(exc), file=sys.stderr)
        return 2
    print(output)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))

Complete shared command sequence

Save as code/sequence.py. Every command has a manual observation pause. The same sequence generates the constructed CSV and timing illustration.

"""Single-output commands shared by host construction and optional Pico adapter."""
INPUTS = ("a", "b", "c", "d", "up", "down", "clr", "load_n")


def events():
    x = dict.fromkeys(INPUTS, 0)
    out = []
    def put(k, v, label):
        if x[k] == v:
            raise ValueError("command must change one output")
        x[k] = v
        out.append((dict(x), label))
    put("clr", 1, "clear asserted: Q=0; do not infer power-up state")
    put("up", 1, "UP idle HIGH under clear")
    put("down", 1, "DOWN idle HIGH under clear")
    put("load_n", 1, "load inactive under clear")
    put("clr", 0, "release clear with both clocks HIGH")
    put("b", 1, "prepare B for binary1110 while load inactive")
    put("c", 1, "prepare C")
    put("d", 1, "prepare D; A remains0")
    put("load_n", 0, "asynchronous load14 without a count edge")
    put("load_n", 1, "release load with stable data and clocks")
    for name, label in (("up", "14 to15"), ("up", "15 to0"),
                        ("down", "0 to15"), ("down", "15 to14")):
        put(name, 0, label + ": LOW half; inspect terminal flag")
        put(name, 1, label + ": rising edge; inspect count")
    return out


def pad_fast_4ma(old):
    return (old & ~0x31) | 0x11


def safe_low(write):
    # Inhibit counting through asynchronous load BEFORE lowering clocks.
    for name in ("load_n", "clr", "a", "b", "c", "d", "up", "down"):
        write(name, 0)


def run(write, wait_ms, pause, observe):
    old = dict.fromkeys(INPUTS, 0)
    for index, (state, label) in enumerate(events()):
        name = next(k for k in INPUTS if state[k] != old[k])
        write(name, state[name])
        wait_ms(200)  # human observation pacing, NEVER an edge/timing certificate
        observe(index, name, state[name], label)
        pause(label)
        old = state

Optional complete Pico adapter

Save as code/pico_sequence.py, with sequence.py alongside it on the Pico. Do not call it main.py or arrange unattended boot execution. Run it manually from the MicroPython console only after the power/grounding procedure. RP2 is MicroPython's RP2040-family port, its hardware-specific implementation. That exact port's Pin constructor supports Pin(number,Pin.OUT,value=0); it has no assumed portable drive/slew keyword here. mem32 accesses32-bit registers. RP2040 PADS_BANK0 starts at 0x4001C000, with GPIO n at offset 4+4n. Setting drive bits5:4 to 01 selects 4 mA; bit0 selects fast slew. The mask changes only those bits and reads them back. Readback proves register selection, not an analog edge. If board/version/readback fails, keep external5 V OFF.

"""Original RP2040 Pico; MicroPython1.26.0. Manual launch, never main.py."""
from machine import Pin, mem32
from time import sleep_ms
from os import uname
import sys
from sequence import run, pad_fast_4ma, safe_low

GPIO = {"a": 2, "b": 3, "c": 4, "d": 5,
        "up": 6, "down": 7, "clr": 8, "load_n": 9}
PADS_BANK0 = 0x4001C000


def main():
    if "RP2040" not in uname().machine or sys.implementation.version[:3] != (1, 26, 0):
        raise RuntimeError("Original RP2040 Pico / MicroPython1.26.0 required")
    pins = {}
    # External5V MUST be OFF throughout initialization and any exception here.
    for name, number in GPIO.items():
        pins[name] = Pin(number, Pin.OUT, value=0)
        address = PADS_BANK0 + 4 + 4 * number
        mem32[address] = pad_fast_4ma(mem32[address])
        if mem32[address] & 0x31 != 0x11:
            raise RuntimeError("Pad readback failed: keep external5V OFF")
    def write(name, value):
        pins[name].value(value)
    try:
        input("All eight commands LOW. Verify wiring, then enable shared5V. "
              "Qualify levels/edges/rail before counting. Enter to assert CLR: ")
        run(write, sleep_ms, lambda text: input(text + "; Enter: "),
            lambda i,k,v,text: print("COMMAND ONLY", i, k, v, text))
    finally:
        safe_low(write)
        print("Commands LOW; external5V OFF next, then Pico USB OFF before rewiring.")


if __name__ == "__main__":
    main()

Complete host tests

Save as tests/test_protocol.py. These 29 tests exercise all sixteen parallel loads and both directions, transparent loading, clear priority, forbidden protocols, parser/late-file failures, blank/unqualified observations and actual controller ordering. One test checks all 256 eight-direction words from each of sixteen starting values—32,768 directional steps,65,536 clock transitions—against a signed-step arithmetic oracle. Another executes the actual adapter with explicit host doubles (substitute hardware interfaces running on the computer) to check its register mask and exception cleanup. Host doubles are not RP2 execution or a firmware build.

"""Host behavior only; no target or analog qualification."""
import csv
import io
import pathlib
import subprocess
import sys
import tempfile
import unittest
import itertools
import types
from unittest.mock import patch
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "code"))
from hc193_protocol import Counter, analyze, FIELDS
from sequence import events, run, pad_fast_4ma, safe_low

BASE = dict(a=0,b=0,c=0,d=0,up=1,down=1,clr=0,load_n=1)

def loaded(n):
    x = dict(BASE)
    for bit, name in enumerate("abcd"):
        x[name] = (n >> bit) & 1
    x["load_n"] = 0
    m = Counter(); m.step(x)
    x["load_n"] = 1; m.step(x)
    return m, x

class Logic(unittest.TestCase):
    def test_unknown_start(self):
        self.assertIsNone(Counter().step(BASE)["count"])
    def test_clear_priority(self):
        x = dict(BASE,clr=1,load_n=0,a=1,b=1,c=1,d=1)
        self.assertEqual(Counter().step(x)["count"],0)
    def test_all_parallel_loads(self):
        for n in range(16):
            m,x=loaded(n); self.assertEqual(m.q,n)
    def test_data_is_not_count(self):
        m,x=loaded(5);x["a"]=0
        self.assertEqual(m.step(x)["count"],5)
    def test_transparent_load(self):
        m,x=loaded(0);x["load_n"]=0;m.step(x);x["d"]=1
        self.assertEqual(m.step(x)["count"],8)
    def test_load_release_and_data_refused(self):
        m,x=loaded(0);x["load_n"]=0;m.step(x);x.update(load_n=1,a=1)
        with self.assertRaises(ValueError):m.step(x)
    def test_every_up_and_down(self):
        for n in range(16):
            for clock, delta in (("up",1),("down",-1)):
                m,x=loaded(n);x[clock]=0
                self.assertEqual(m.step(x)["count"],n)
                x[clock]=1;self.assertEqual(m.step(x)["count"],(n+delta)%16)
    def test_terminal_flags_low_half_only(self):
        m,x=loaded(15);self.assertEqual(m.step(x)["carry_n"],1)
        x["up"]=0;self.assertEqual(m.step(x)["carry_n"],0)
        x["up"]=1;self.assertEqual(m.step(x),dict(count=0,carry_n=1,borrow_n=1))
        x["down"]=0;self.assertEqual(m.step(x)["borrow_n"],0)
        x["down"]=1;self.assertEqual(m.step(x)["count"],15)
    def test_other_clock_must_be_high(self):
        m,x=loaded(4);x["up"]=0;m.step(x);x["down"]=0
        with self.assertRaises(ValueError):m.step(x)
    def test_simultaneous_clocks_refused(self):
        m,x=loaded(4);x.update(up=0,down=0)
        with self.assertRaises(ValueError):m.step(x)
    def test_unknown_rising_refused(self):
        m=Counter();x=dict(BASE);m.step(x);x["up"]=0;m.step(x);x["up"]=1
        with self.assertRaises(ValueError):m.step(x)
    def test_invalid_bit_and_extra_key(self):
        for bad in [dict(BASE,a=2),dict(BASE,a=True),dict(BASE,z=0)]:
            with self.assertRaises(ValueError):Counter().step(bad)
    def test_clear_release_with_clock_refused(self):
        m=Counter();x=dict(BASE,clr=1,up=0);m.step(x);x.update(clr=0,up=1)
        with self.assertRaises(ValueError):m.step(x)
    def test_async_clear_no_edge(self):
        m,x=loaded(11);x["clr"]=1;self.assertEqual(m.step(x)["count"],0)

    def test_exhaustive_direction_words(self):
        for start in range(16):
            for word in itertools.product(("up", "down"), repeat=8):
                m,x=loaded(start); signed=0
                for name in word:
                    x[name]=0; before=m.step(x)
                    expected=(start+signed)%16
                    self.assertEqual(before["count"],expected)
                    self.assertEqual(before["carry_n"],int(not(expected==15 and name=="up")))
                    self.assertEqual(before["borrow_n"],int(not(expected==0 and name=="down")))
                    signed += 1 if name=="up" else -1
                    x[name]=1;self.assertEqual(m.step(x)["count"],(start+signed)%16)

class Reader(unittest.TestCase):
    def rows(self):
        return [{**{k:str(v) for k,v in s.items()},"step":str(i),"kind":"constructed",
                 "qualified":"no","observed_count":"","observed_carry_n":"",
                 "observed_borrow_n":""} for i,(s,_) in enumerate(events())]
    def test_constructed_sequence(self):
        out=analyze(self.rows());self.assertEqual(out[-1]["expected_count"],14)
        self.assertIn(0,[r["expected_carry_n"] for r in out]);self.assertIn(0,[r["expected_borrow_n"] for r in out])
    def test_blank_observation_not_pass(self):
        out=analyze(self.rows());self.assertTrue(all(x["comparison"]=="not_observed" for x in out))
    def test_unqualified_measurement_no_comparison(self):
        rows=self.rows();rows[0].update(kind="measured",observed_count="0")
        self.assertEqual(analyze(rows)[0]["comparison"],"withheld_unqualified")
    def test_qualified_match_and_mismatch(self):
        rows=self.rows();rows[0].update(kind="measured",qualified="yes",observed_count="0")
        self.assertEqual(analyze(rows)[0]["comparison"],"match")
        rows[0]["observed_count"]="1";self.assertEqual(analyze(rows)[0]["comparison"],"mismatch")
    def test_constructed_observations_refused(self):
        rows=self.rows();rows[0]["observed_count"]="0"
        with self.assertRaises(ValueError):analyze(rows)
    def test_bad_step_and_nan_refused(self):
        for field,value in [("step","1"),("a","nan"),("observed_count","16"),("qualified","maybe")]:
            rows=self.rows();rows[0][field]=value
            with self.assertRaises(ValueError):analyze(rows)
    def test_late_failure_no_partial_cli(self):
        rows=self.rows();rows[-1]["up"]="2"
        self.cli(rows,2)
    def cli(self,rows,code):
        with tempfile.TemporaryDirectory() as td:
            p=pathlib.Path(td)/"a.csv"
            with p.open("w",newline="") as f:
                w=csv.DictWriter(f,fieldnames=FIELDS);w.writeheader();w.writerows(rows)
            r=subprocess.run([sys.executable,str(pathlib.Path(__file__).resolve().parents[1]/"code/hc193_protocol.py"),str(p)],capture_output=True,text=True)
            self.assertEqual(r.returncode,code);self.assertNotIn("Traceback",r.stderr)
            if code:self.assertEqual(r.stdout,"")
    def test_valid_cli(self):self.cli(self.rows(),0)
    def test_unclosed_header_cli(self):
        with tempfile.TemporaryDirectory() as td:
            p=pathlib.Path(td)/"bad.csv";p.write_text('"unclosed')
            r=subprocess.run([sys.executable,str(pathlib.Path(__file__).resolve().parents[1]/"code/hc193_protocol.py"),str(p)],capture_output=True,text=True)
            self.assertEqual(r.returncode,2);self.assertEqual(r.stdout,"");self.assertNotIn("Traceback",r.stderr)

class Controller(unittest.TestCase):
    def test_each_step_one_output_and_observe_before_cleanup(self):
        writes=[];seen=[]
        run(lambda k,v:writes.append((k,v)),lambda t:self.assertGreaterEqual(t,200),lambda t:None,
            lambda i,k,v,t:seen.append((i,len(writes))))
        self.assertEqual(len(seen),len(events()))
        self.assertEqual(seen[-1][1],len(events()))
        states=[s for s,_ in events()]
        self.assertTrue(all(sum(a[k]!=b[k] for k in a)==1 for a,b in zip(states,states[1:])))
    def test_safe_low_order(self):
        out=[];safe_low(lambda k,v:out.append((k,v)))
        self.assertEqual(out[0],("load_n",0));self.assertEqual(set(out),{(k,0) for k in BASE})
    def test_pad_bits_preserved(self):
        for old in range(256):self.assertEqual(pad_fast_4ma(old),(old & ~0x31)|0x11)
    def test_pause_failure_propagates(self):
        def stop(t):raise KeyboardInterrupt()
        with self.assertRaises(KeyboardInterrupt):run(lambda k,v:None,lambda t:None,stop,lambda *a:None)

    def test_pico_adapter_host_doubles_cleanup(self):
        # Actual adapter source exercised with host doubles, NOT a Pico run/build.
        log=[]
        class Pin:
            OUT=1
            def __init__(self,n,mode,value):self.n=n;log.append((n,value))
            def value(self,v):log.append((self.n,v))
        machine=types.ModuleType("machine");machine.Pin=Pin
        class Memory(dict):
            def __getitem__(self,k):return dict.get(self,k,0xC2)
        machine.mem32=Memory()
        path=pathlib.Path(__file__).resolve().parents[1]/"code/pico_sequence.py"
        space={"__name__":"host_double_only"}
        with patch.dict(sys.modules,{"machine":machine}),patch("time.sleep_ms",lambda t:None,create=True):
            exec(compile(path.read_text(),str(path),"exec"),space)
        space["uname"]=lambda:types.SimpleNamespace(machine="Raspberry Pi Pico with RP2040")
        with patch.object(sys,"implementation",types.SimpleNamespace(version=(1,26,0))),patch("builtins.input",side_effect=["",KeyboardInterrupt()]):
            with self.assertRaises(KeyboardInterrupt):space["main"]()
        self.assertEqual(log[:8],[(n,0) for n in range(2,10)])
        self.assertEqual(log[-8:],[(9,0),(8,0),(2,0),(3,0),(4,0),(5,0),(6,0),(7,0)])
        for n in range(2,10):self.assertEqual(machine.mem32[0x4001C000+4+4*n],0xD3)

if __name__=="__main__":unittest.main()

If the result looks wrong

  • Two steps or an unexpected direction: stop. Check the inactive clock at the U1 pin, repeated threshold crossings and mismatched ground/reference; do not fix the model to match an unqualified waveform.
  • Every low half changes Q: check that UP/DOWN pin numbers and polarity were not swapped with a different counter variant. This part counts on rising edges.
  • Data changes Q while you meant to count: LOAD_N may still be LOW. Verify its actual pin voltage and release timing.
  • Q stays0: CLR is active HIGH. Check U3 pin 8→U1 pin 14 before blaming a dead counter.
  • Carry never goes LOW at 15: check it during UP LOW, not just after UP rises. Borrow likewise needs count 0 and DOWN LOW.
  • AHCT HIGH too low: remove unauthorized pulls/loads, verify the shared rail and actual total leakage/resistance; the 8 mA table is not the 50 µA table.
  • A shutdown or reboot occurred: discard the run as qualified evidence. Clear/load initialization must be repeated; neither input pulls nor ideal host state establish the real chip's power-up state.
  • Analyzer refuses a jump: preserve the original file. Record the missing separate commands in a new constructed file or repeat the physical run. Never invent unobserved transitions.

Challenge: a terminal signal is not a stored overflow bit

At a held count 15 with both clocks HIGH, someone observes CO_N HIGH and says the counter is not at its terminal count. Is that conclusion valid? Then they lower UP and observe CO_N LOW, but Q still reads15. Which action changes the stored count, and why must DOWN remain HIGH?

Full answer

The conclusion is invalid. In the normal count mode, CO_N is LOW only when the count is 15 and UP is LOW. It is therefore HIGH at a held15 with UP HIGH. Lowering UP enables the terminal low interval without taking the count edge; Q remains15. Raising UP is the positive edge that wraps the count to 0, provided DOWN stayed HIGH and clear/load were inactive with valid timing. CO_N then returns HIGH. DOWN HIGH is part of the device's direction-steering condition, not an optional idle preference. Pulsing both clocks does not request a useful “cancelled” net count. The same reasoning mirrors at count 0 with DOWN/BO_N. The experiment demonstrates a protocol and terminal pulse, not a general safe asynchronous event merger or a completed cascade design.

Primary references and useful next reading

TI SN54HC193/SN74HC193, SCLS122D, current official Rev.D: pinout/ordering pp1–2, clear priority and clock sequence p4, recommended/electrical/timing limits pp5–8. Current exact SN74HC193N product record identifies ACTIVE N/PDIP16; an errata search found no separate device errata, not proof none exists. Do not substitute Q1, LS or a decimal-family truth table.

TI SN74AHCT125, SCLS264R(February2024),§4/§5 and function table; exact N package. TI slow/floating CMOS-input guidance and TI power-up state guidance explain why idle pulls and software state are not sufficient evidence.

Raspberry Pi RP2040 datasheet, Release 13(19November2026),§2.19.6.3 pad registers and§5.5.3 I/O characteristics; official original Pico pinout. MicroPython1.26.0 RP2 documentation and that release's actual Pin implementation support the adapter API, not a claim of target validation.

RIGOL DHO800 user guide,§1.1 and§4.3.2 for mandatory rear grounding and supplied adapter; PVP2150 user guide for10X loading/compensation; Keysight34460/61/65/70 A data sheet for fixed-range input resistance. Actual instrument configuration and loading still have to be recorded.

Related published lessons: button debounce and hysteresis explains why raw contacts are not clocks; cable delay versus scope path bias develops a separate physical measurement question. The present lesson neither measures propagation delay nor imports an undocumented scope format.

Reader files and verification: the reader includes literal source, full model/controller/tests, two editable diagrams and their PNGs, constructed commands and blank worksheets. No physical result or target execution is claimed.