Download and extract the reader ZIP archive (a compressed collection of files). Links labelled “reader ZIP; extract …” download this archive; after extraction, open the named file. The archive includes full-size Portable Network Graphics (PNG) images, editable diagrams, complete code and worksheets.
A signal can change while a memory bit stays still. The useful question is not “Is the data HIGH?” but “Has the event that stores it happened?” This experiment separates those questions with a Texas Instruments SN74HC74N integrated circuit (IC), a chip containing two independent one-bit storage elements. We use one of them.
A bit is a binary value, 0 or 1. A D-type flip-flop stores the logic level on its data input, D, at a qualifying clock event. A clock, labelled CLK on this chip, is a timing signal; a rising edge is its transition from logic 0 (LOW) to logic 1 (HIGH). This part is positive-edge-triggered: holding the clock HIGH does not make the output follow D. Its Q output represents the stored bit. Q_N labels the complementary output in the valid states used below; the suffix _N marks an inverted signal or an active-LOW command, as specified for each pin.
Active LOW means a command is asserted by a low voltage. CLR_N is asynchronous clear: it forces Q LOW without waiting for a clock edge. PRE_N is asynchronous preset, which could force Q HIGH, but this fixture keeps it permanently HIGH and inactive. “Asynchronous” here means independent of the clock, not free of timing restrictions when the command is released.
The source is an original Raspberry Pi Pico with an RP2040 microcontroller (a programmable control chip) and MicroPython 1.26.0 (Python for small microcontrollers). General-purpose input/output (GPIO) pins make three slow, manually paced commands. Universal Serial Bus (USB) powers the Pico and provides its console. The logic ICs use a separate regulated 5 V rail and a documented interface; no 5 V output connects to a Pico input. Complete host-tested Python is an ideal model and protocol checker, not evidence that a physical circuit worked. No firmware build, target execution, assembled board, captured waveform or measured timing is claimed.
Parts, units and the interface choice
A volt (V) measures potential difference; an ampere (A) measures current. A milliampere (mA) is one thousandth of an ampere and a microampere (µA) one millionth. An ohm (Ω) is a unit of resistance; a kilohm (kΩ) is 1,000 Ω. A watt (W) is a unit of power, the rate of energy transfer. A farad measures capacitance; a nanofarad (nF) is one billionth of a farad. Direct current (DC) denotes the steady-polarity supply and voltage measurements here.
The HC family is high-speed complementary metal-oxide-semiconductor (CMOS) logic. Its input HIGH requirement is not automatically met by every nominal 3.3 V source. The AHCT family is advanced high-speed CMOS with transistor-transistor logic (TTL)-compatible input thresholds. That describes the selected buffer’s electrical interface; it is not permission to substitute any similarly named HC, HCT, AHC, automotive or different-manufacturer part.
| Part | Quantity | Role |
|---|---|---|
| TI SN74HC74N, N 14-pin plastic dual-inline package (PDIP) | 1 | U1: one positive-edge storage element; second element has defined unused inputs. |
| TI SN74AHCT125N, N PDIP14 | 1 | U2: three non-inverting buffers (each copies its input logic state using the logic-rail output driver) translate D, CLK and CLR_N to the shared logic rail. Output enable (OE_N) is hard-wired LOW. |
| Original Pico RP2040, MicroPython 1.26.0 | 1 | Three GPIO commands; never reads a 5 V output. |
| 10 kΩ, 1%, at least 0.25 W resistors | 3 | Pull only the three U2 input-side nodes to ground when the Pico is not driving. |
| 100 nF ceramic capacitor, at least 10 V rating | 2 | One capacitor directly between pins 14 and 7 of each logic chip supplies brief switching current locally; this is called bypassing. |
| Isolated regulated low-voltage supply; example SIGLENT SPD3303X independent CH1 | 1 | 5.0 V setting, configured 40 mA limit; measure 4.9–5.1 V at each IC. Other channels/tracking off. The configured limit is not a pin-current allowance or a measured fault guarantee. |
| Keysight 34461A digital multimeter (DMM), fixed 10 V DC range, 10 MΩ input mode | 1 | Check supply and stable output voltages using HI (positive voltage input) and LO (reference) terminals, never a current socket. |
| RIGOL DHO804 oscilloscope with compensated PVP2150 probes in 10X mode | 1 set | Qualify actual pin voltages, individual edges and slower event separation in separate acquisitions. Confirm probe/attenuation settings and instrument uncertainty before using a result. |
The exact TI ordering pages list both N-package parts ACTIVE at the source check. The current HC74 datasheet is SCLS094F (June 2021); AHCT125 is SCLS264R (February 2024). Manufacturer documentation and a targeted errata search did not reveal a separate device-specific errata sheet; that search is not a guarantee that no later notice exists. The current RP2040 document read was Release 13, built November 19, 2026. Recheck these identities before substituting hardware. HC74 recommends2–6V supply and AHCT1254.5–5.5V; their7V absolute supply maximum is a stress rating, not an operating target. The absolute25mA output-current stress limit is not the small-load operating budget used here.
Trace the whole signal path before applying power
Mandatory oscilloscope setup before signal connections: Power the DHO804 only with its supplied 15 V, 3 A adapter. Its Type-C power lead does not provide protective earth, the equipment safety-ground connection: connect the supplied grounding lead from the 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 all probe ground clips to G0. The fixture label G0 is not an instruction to guess a protective-earth connection from a bench-supply terminal.
Download the original editable Scalable Vector Graphics (SVG) schematic — reader ZIP; extract sn74hc74-edge-storage-reader/assets/edge-storage-circuit.svg and full-size Portable Network Graphics (PNG) image. The schematic is functional, not a physical breadboard layout. V5 is the shared logic supply; G0 is the common voltage reference. VCC is each chip’s positive supply pin and GND its ground pin. The label 3V3 means nominal3.3V; it is not a separate5V power connection. Every G0 symbol is the same connected net, a group of joined terminals. NC means not connected: an unused output can be open, while an unused input must have a defined voltage.

| Net or pin | Exact connection | Purpose |
|---|---|---|
| V5 / G0 | Supply CH1+ → U1 pin14 and U2 pin14; CH1− → both pin7, Pico physical3, meter LO and all probe ground clips. | Common low-voltage reference. Do not join V5 to Pico 3V3 OUT, VBUS or VSYS. |
| D_3V3 → D | Pico GP2 physical4 → U2 1A pin2; R1 10 kΩ from that input to G0. U2 1Y pin3 → U1 1D pin2. | Translate data without inversion. |
| CLK_3V3 → CLK | GP3 physical5 → U2 2A pin5; R2 10 kΩ input-to-G0. U2 2Y pin6 → U1 1CLK pin3. | Translate clock; the HC74 sees its rising edge. |
| CLR_3V3 → CLR_N | GP4 physical6 → U2 3A pin9; R3 10 kΩ input-to-G0. U2 3Y pin8 → U1 1CLR pin1. | LOW asserts reset; HIGH releases it. |
| All U2 enables / spare gate | U2 pins1,4,10,13 → G0. Spare input12 → G0; spare output11 open. | These buffers could have a third, high-impedance (not actively driving) state if disabled. They are always enabled while properly powered here; no enable-switching experiment. |
| U1 active half | PRE_N pin4 → V5. Observe Q pin5 and Q_N pin6 separately; never join the outputs. | Preset cannot be commanded LOW in this fixture. |
| U1 unused half | D12, CLK11 and CLR_N13 → G0; PRE_N10 → V5. Outputs9 and8 open. | Defined inputs; clear active once valid power and logic levels exist. |
| C1 and C2 | Each 100 nF directly across its own chip’s VCC14 and GND7. | Short local transient-current path; a capacitor at the far end of a breadboard is not equivalent placement. |
Find each package notch and count pins from the top view in its own datasheet. Similar 14-pin packages are not pin-function substitutes. Use short connections. The scope diagram shows one probe on Q; move voltage observations to other named nodes only with power off. A four-channel capture can compare data, clock, clear and Q; Q_N can be examined in a repeat run. All probe ground clips go to G0, never to a signal or positive rail. The supply must be an isolated low-voltage output; this is not a mains experiment.
Why the buffer is necessary—and what the arithmetic does not prove
The RP2040 table at an input/output supply of 3.3 V gives a minimum output HIGH of 2.62 V and a maximum LOW of 0.5 V at the current selected by its drive setting. Configure 4 mA drive in the adapter. For AHCT inputs, HIGH must reach at least 2.0 V and LOW at most 0.8 V: the tabulated DC planning margins are 0.62 V and 0.30 V. The unbuffered HC74 would require 3.15 V HIGH even at its 4.5 V table point, so the Pico’s documented minimum would not meet it.
A nominal3.3V HIGH also increases the AHCT device’s own5V supply current relative to rail-level inputs: its extra-current table tests one input at3.4V and allows up to1.5mA. We do not treat the chip’s supply current as zero or infer a measured three-input total from that row. Check that the rail remains in range. The 10 kΩ input resistor is a small GPIO load, not a resistor on a 5 V buffer output. With a deliberately conservative 3.4 V input and a 9.9 kΩ minimum resistance, I = 3.4/9,900 ≈ 0.344 mA, plus up to 1 µA buffer input leakage. Resistor power is 3.4²/9,900 ≈ 0.00117 W, comfortably below 0.25 W. This is a load calculation, not a measurement of a particular Pico or a guarantee of the actual 3V3 rail.
The AHCT table gives at least 4.4 V HIGH and at most 0.1 V LOW at a 4.5 V supply and a 50 µA output test load. The HC74’s 6 V HIGH requirement, 4.2 V, is a conservative planning comparison for our lower rail; its 4.5 V LOW limit is 1.35 V. We do not manufacture a new guaranteed 5.0 V datasheet row. Actual pin levels remain a required check. In particular, the AHCT 8 mA HIGH bound of 3.8 V cannot be substituted into the 4.4 V calculation.
Keep total DC load on each buffer output below 50 µA. One HC input contributes at most 1 µA leakage. Even conservatively allowing two measurement paths of at least 1 MΩ each gives 1 + 2×5.1/1,000,000 = 11.2 µA. The specified 10 MΩ meter mode and 10X probe are lighter still, about 2.03 µA including the HC input when both are attached. There is no output-side 10 kΩ resistor: that alone would draw roughly 0.5 mA and invalidate the 50 µA argument. The HC74 Q/Q_N observation load should remain below its own 20 µA small-load table condition; the two ≥1 MΩ measurement paths total at most 10.2 µA. Do not attach indicator lamps, another interface or an unknown termination.
Input capacitance and wiring also matter. The HC74 input is specified up to 10 pF; the PVP2150 10X probe is 10 pF ±5 pF. A 50 pF buffer switching table assumes a total capacitive load that includes wiring and instruments. We do not certify breadboard capacitance or quote its table delay as a measured delay. Keep the fixture short and qualify the resulting waveform. Never select a 50 Ω termination or 1X probe simply because the trace looks convenient.
A slow repetition rate does not create a clean clock edge
A millisecond (ms) is one thousandth of a second; a nanosecond (ns) is one billionth. Setup time is the interval that data must be stable before the capturing edge; hold time is the required stability afterward. Recovery is the required separation between releasing an asynchronous command and a following active clock edge; removal concerns release just after an active edge. The selected datasheet lists PRE/CLR inactive-before-clock setup; we do not invent a separate numeric removal specification. This protocol releases clear while the clock stays LOW, far from both adjacent rising edges. Neither a printed command nor a long software delay measures these physical intervals.
Temperature below uses degrees Celsius (°C). At 4.5 V over the HC74’s −40 to 85 °C table range, its minimum clear-low pulse is 25 ns, clock HIGH/LOW pulse 20 ns, data setup 25 ns and clear-inactive setup 6 ns; data hold is 0 ns in that table. These are the stated test conditions, not a new 5.0 V rating. We use a very different teaching protocol: change one input at a time, wait at least 200 ms before the next change, and never change clear while clock is HIGH. The physical trial must additionally demonstrate stable data, clock pulses and clear-release separation of at least 1 ms at the IC pins. That large deliberate separation keeps this lesson away from a boundary experiment; it does not replace the manufacturer’s electrical conditions.
The AHCT125 still requires input transition rate Δt/Δv no slower than 20 ns/V. Its inputs are not claimed to be Schmitt-trigger inputs, which use distinct rising and falling thresholds to resist noise. The Pico adapter selects fast slew, meaning its configured output transition mode, using RP2040 PADS_BANK0 at 0x4001C000. GPIO2/3/4 pad offsets are 0x00C/0x010/0x014; DRIVE bits5:4=01 selects 4mA and SLEWFAST bit0=1 selects fast. Other bits are preserved and selected bits are read back. It uses the documented machine.mem32 register interface, not a port-dependent Pin drive/slew keyword. These register settings and readback do not supply a numeric measured edge guarantee. Check actual rise/fall rate and one clean threshold crossing at U2 pins 2,5,9. Separately qualify every driven HC74 input—D pin 2, CLK pin 3 and CLR_N pin 1—for valid HIGH/LOW levels, rise/fall no slower than 400 ns, one threshold crossing per commanded transition and no overshoot beyond the allowed input range. The 400 ns limit is conservative relative to both the 4.5 V and 6 V table points; it is not a clock-only condition. A slow, bouncing manual clock button is not an alternative source.
Make two acquisitions: a fast timebase at the relevant pins for transitions and ringing, and a slower record for millisecond ordering. Zooming a long, under-sampled record cannot recover missed edges. Set the scope and probe both to 10X, compensate each probe on the instrument’s reference first, use short ground springs, document bandwidth/sample rate/trigger and uncertainty, and leave bandwidth limiting off for the edge check. If the DHO804/probe/record setup cannot resolve a required condition with margin, the physical trial stays unqualified; retain the offline lesson without interpreting a pass/fail from the hardware. A DMM confirms stable voltages but cannot qualify edge crossings.
Bring up a known state before the sequence
- With USB and the external output disconnected, inspect every pin, resistor and bypass. Verify that V5 and G0 are not shorted and that no V5 signal reaches a Pico GPIO. Confirm PRE_N4 HIGH wiring and the unused-half ties. Connect the isolated supply’s negative terminal, Pico ground and instrument ground returns to G0.
- Install the three complete files in
code/on the original Pico running MicroPython 1.26.0. Run manually from its console; do not name this demonstrationmain.pyor arrange automatic startup. With the external logic rail OFF, useimport pico_sequence; pico_sequence.main(). It checks RP2040/version, drives D/CLK/CLR command pins LOW and pauses. - Enable the common logic rail and verify 4.9–5.1 V at both chips with the meter. Keep all three commands LOW while checking. The pull resistors define the buffer inputs, but power-up transitions are not valid stored-state evidence. Wait for the rail to settle, verify actual CLR_N LOW and PRE_N HIGH at U1, and verify Q LOW/Q_N HIGH. If that baseline is absent, turn off and diagnose; do not “fix” it by random clocking.
- Qualify the actual logic levels and waveforms described above in a separate initial trial. Use the provided qualification worksheet for real readings and uncertainty. The AHCT input-current table includes VCC from 0 to 5.5 V, but this is not a claim of guaranteed powered-off output isolation or whole-fixture backpower immunity. Keep all three GPIO commands LOW during power changes. Both logic ICs share the same rail; never power one while deliberately driving it from the other at an unrelated rail.
- Repeat from the established reset baseline. At each prompt, the previous state is held for inspection; pressing Enter makes the displayed next change, waits 200 ms, then prints a command report. Read both output states only after settling. Every command report is labelled COMMAND ONLY, not a measurement. The final prompt holds the restored captured HIGH until you explicitly finish.
- The normal or interrupted exit lowers CLK, asserts clear, then lowers D. Confirm those LOW commands, turn the external rail OFF, then disconnect USB. Unexpected loss of control, a wiring fault or a failed instrument check calls for output OFF—not reliance on software as a protective interlock. Power off before moving a wire or probe.
The finite experiment and its constructed prediction
Start with D=0, CLK=0, CLR_N=0 and PRE_N=1. Releasing clear with CLK LOW leaves the cleared bit LOW; a release is not a clock. Set D HIGH with CLK still LOW: Q should remain LOW. Raise CLK: the bit becomes HIGH. Change D LOW while CLK remains HIGH: Q should remain HIGH. Lowering CLK should also hold HIGH. Only the next rising edge stores the LOW data.
Then store HIGH again, lower CLK and assert clear. Q should fall although no clock edge occurred. Release clear while CLK remains LOW and wait before the restored rising edge. That final edge stores HIGH again. The complete command sequence is fixed in sequence.py; preset is never exercised.

sn74hc74-edge-storage-reader/assets/constructed-edge-timing.svg.| Constructed coordinate / action | D / CLK / CLR_N | Q / Q_N expected | Reason |
|---|---|---|---|
| 0: explicit reset | 0 / 0 / 0 | 0 / 1 | Clear asserted after valid power. |
| 200: release clear;400: D HIGH | 0→1 / 0 / 1 | 0 / 1 | No capturing edge. |
| 600: CLK rises | 1 / 1 / 1 | 1 / 0 | Capture HIGH. |
| 800: D LOW;1000: CLK falls | 0 / 1→0 / 1 | 1 / 0 | Both events hold the bit. |
| 1200: CLK rises | 0 / 1 / 1 | 0 / 1 | Capture LOW. |
| 1400: CLK LOW;1600: D HIGH;1800: CLK rises | 1 / 1 / 1 | 1 / 0 | Store HIGH again. |
| 2000: CLK LOW;2200: clear LOW | 1 / 0 / 0 | 0 / 1 | Asynchronous clear, no clock. |
| 2400: clear HIGH;2600: CLK rises | 1 / 0→1 / 1 | 0→1 / 1→0 | Release holds LOW; later edge captures HIGH. |
The rule is conditional, not a complete transistor-level simulator: with PRE_N fixed HIGH, CLR_N LOW forces Q=0; otherwise a valid LOW→HIGH clock transition sets Q=D; all other permitted events hold Q. Q_N=1−Q is used only in these valid states. The datasheet’s forbidden simultaneous LOW preset/clear condition produces both outputs HIGH and is nonstable on release. The model neither pretends they are complementary there nor tests that state: its fixed-PRE fixture does not accept a preset column. Do not alter the wiring to create it.
Complete programs and what the checker refuses
Extract the reader ZIP archive, a compressed bundle. Keep the three code files together. On a host with CPython 3.9 or later (the standard desktop Python implementation), the commands below run the complete tests and analyze the constructed worksheet. Output is JavaScript Object Notation (JSON), a structured text data format. The checker does not open an instrument, control a GPIO, acquire a waveform or prove a qualification declaration.
python3 -m unittest discover -s tests -v
python3 code/hc74_events.py constructed-example.csv
# On the qualified original Pico only, from the console:
# import pico_sequence; pico_sequence.main()
CSV headers and binary fields must match exactly. Event coordinates are nonnegative integer milliseconds, not nanosecond timestamps. The first record must be the explicit reset baseline at zero; later records need at least 200 ms separation and at most one input change. Clear transitions require clock LOW before and after. These are this experiment’s record/protocol constraints. They cannot establish actual slew, setup, hold, recovery, supply or load conditions.
Use kind=constructed,edge_qualification=not_applicable for invented examples. For a real record, use kind=measured and keep edge_qualification=unqualified until the separate physical checks are documented. Measured unqualified rows retain their ideal expectations but withhold every observation/model comparison. declared_qualified is an operator declaration, not validation performed by the software. Both observations may be blank, but a partial pair is refused. Noncomplementary observed pairs are retained as anomalies, not silently repaired.
A malformed header or row, extra column, invalid state, mixed provenance, bad time or excessive input raises a controlled refusal. The command line exits2 and writes no JSON on refusal; normal output exits0. An unexpected observed state is a reason to inspect qualification and wiring, not to claim metastability, a defective IC or a new logic rule.
Complete offline checker: code/hc74_events.py
"""Offline HC74 fixture protocol model. It does not acquire or qualify hardware."""
import argparse
import csv
import io
import json
import re
import sys
FIELDS = ["t_ms", "d", "clk", "clr_n", "q_observed", "qbar_observed",
"kind", "edge_qualification"]
LIMIT = 65536
GUARD_MS = 200
def binary(value, label):
if value not in ("0", "1"):
raise ValueError(label + " must be binary 0 or 1")
return int(value)
def analyze_csv(text):
"""Return ideal event expectations; unqualified measurements never get a match."""
if len(text.encode("utf-8")) > LIMIT:
raise ValueError("input exceeds 65536 bytes")
try:
reader = csv.DictReader(io.StringIO(text, newline=""), strict=True)
# fieldnames reads the header lazily, so keep it inside the CSV guard.
if reader.fieldnames != FIELDS:
raise ValueError("header must be exactly " + ",".join(FIELDS))
rows = list(reader)
except csv.Error as exc:
raise ValueError("invalid CSV: " + str(exc)) from None
if not 1 <= len(rows) <= 1000:
raise ValueError("need 1 to 1000 event rows")
events = []
previous = None
provenance = None
q = 0
summary = dict(matched=0, mismatched=0, withheld=0, without_observation=0)
for number, row in enumerate(rows, 2):
if set(row) != set(FIELDS) or any(v is None for v in row.values()):
raise ValueError("row %d has missing or extra columns" % number)
if not re.fullmatch(r"(?:0|[1-9][0-9]{0,8})", row["t_ms"]):
raise ValueError("t_ms must be a plain integer from 0 to 999999999")
t = int(row["t_ms"])
d, clk, clear = [binary(row[k], k) for k in ["d", "clk", "clr_n"]]
kind, qualification = row["kind"], row["edge_qualification"]
if kind == "constructed":
if qualification != "not_applicable":
raise ValueError("constructed qualification must be not_applicable")
elif kind == "measured":
if qualification not in ("unqualified", "declared_qualified"):
raise ValueError("measured qualification must be unqualified or declared_qualified")
else:
raise ValueError("kind must be constructed or measured")
if provenance is None:
provenance = (kind, qualification)
if provenance != (kind, qualification):
raise ValueError("all rows must have the same kind and qualification")
if previous is None:
if (t, d, clk, clear) != (0, 0, 0, 0):
raise ValueError("initial row must be t_ms=0,d=0,clk=0,clr_n=0")
else:
pt, pd, pc, pr = previous
if t - pt < GUARD_MS:
raise ValueError("fixture protocol needs at least 200 ms between rows")
if sum([d != pd, clk != pc, clear != pr]) > 1:
raise ValueError("change at most one input per event row")
if clear != pr and (clk != 0 or pc != 0):
raise ValueError("change clear only with clock low before and after")
if clear == 0:
q, reason = 0, "async_clear"
elif previous is not None and previous[3] == 0:
reason = "release_hold"
elif previous is not None and previous[2] == 0 and clk == 1:
q, reason = d, "rising_capture"
else:
reason = "held"
qo, qb = row["q_observed"], row["qbar_observed"]
if bool(qo) != bool(qb):
raise ValueError("observations must be a complete pair or both blank")
observed = None if not qo else (binary(qo, "q_observed"), binary(qb, "qbar_observed"))
match = None
if observed is None:
summary["without_observation"] += 1
comparison = "no_observation"
elif kind == "measured" and qualification == "unqualified":
summary["withheld"] += 1
comparison = "withheld_unqualified"
else:
match = observed == (q, 1 - q)
summary["matched" if match else "mismatched"] += 1
comparison = "constructed_consistency" if kind == "constructed" else "conditional_logic_comparison"
events.append(dict(t_ms=t, d=d, clk=clk, clr_n=clear, q_expected=q,
qbar_expected=1-q, reason=reason, match=match,
comparison=comparison,
observations_complementary=None if observed is None else sum(observed) == 1))
previous = (t, d, clk, clear)
return dict(model="SN74HC74 fixture with PRE_N permanently HIGH", events=events,
summary=summary, kind=provenance[0], edge_qualification=provenance[1],
physical_qualification_proven=False,
scope="Ideal stable-event protocol only; milliseconds do not certify analog edges, setup/hold, recovery or propagation.")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("csv_file", help="UTF-8 CSV path, or - for standard input")
args = parser.parse_args()
try:
if args.csv_file == "-":
text = sys.stdin.read(LIMIT + 1)
else:
with open(args.csv_file, encoding="utf-8", newline="") as handle:
text = handle.read(LIMIT + 1)
result = analyze_csv(text)
except (ValueError, UnicodeError, OSError) as exc:
print("Refused: " + str(exc), file=sys.stderr)
return 2
print(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
Complete portable command controller: code/sequence.py
"""Portable finite command sequence; no claim that commanded voltages were observed."""
STEPS = (
("Release clear; clock remains LOW", "clr_n", 1),
("D HIGH while clock LOW: Q should hold LOW", "d", 1),
("First rising edge: store HIGH", "clk", 1),
("D LOW while clock HIGH: Q should hold HIGH", "d", 0),
("Falling edge: Q should hold HIGH", "clk", 0),
("Next rising edge: store LOW", "clk", 1),
("Return clock LOW", "clk", 0),
("D HIGH while clock LOW", "d", 1),
("Rising edge: store HIGH again", "clk", 1),
("Return clock LOW; Q should stay HIGH", "clk", 0),
("Assert clear without a clock edge: Q LOW", "clr_n", 0),
("Release clear; Q stays LOW", "clr_n", 1),
("Restored rising edge: Q HIGH", "clk", 1),
)
def pad_fast_4ma(value):
"""RP2040 DRIVE=01 and SLEWFAST=1, preserving every other bit."""
return (value & ~0x31) | 0x11
def run(writer, wait_ms, prompt, report):
"""Injected callbacks allow host behavior tests without importing machine."""
writer("clk", 0)
writer("d", 0)
writer("clr_n", 0)
try:
for number, (label, key, value) in enumerate(STEPS, 1):
prompt(label)
writer(key, value)
wait_ms(200)
report(number, key, value, label)
prompt("Observe final captured HIGH; Enter to clear and finish")
finally:
writer("clk", 0) # Falling, never a new capture edge.
writer("clr_n", 0)
writer("d", 0)
Complete original-Pico adapter: code/pico_sequence.py
"""Original RP2040 Pico only; MicroPython1.26.0. Run manually, not as 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
GPIO = {"d": 2, "clk": 3, "clr_n": 4}
PADS_BANK0 = 0x4001C000
def main():
if "RP2040" not in uname().machine or sys.implementation.version[:3] != (1, 26, 0):
raise RuntimeError("Use the original RP2040 Pico and MicroPython1.26.0")
pins = {}
for name, number in GPIO.items():
pins[name] = Pin(number, Pin.OUT, value=0)
address = PADS_BANK0 + 4 + 4 * number
# DRIVE bits5:4=01 =>4mA; SLEWFAST bit0=1. Preserve other pad bits.
mem32[address] = pad_fast_4ma(mem32[address])
if (mem32[address] & 0x31) != 0x11:
raise RuntimeError("Pad drive/slew readback failed; keep logic power OFF")
def write(name, value):
pins[name].value(value)
try:
input("Outputs LOW. Verify wiring, then enable the shared logic rail. "
"Verify CLR reset and analog qualification; Enter to step: ")
run(write, sleep_ms, lambda text: input(text + "; Enter: "),
lambda n,k,v,text: print("COMMAND ONLY", n, k, v, text))
finally:
write("clk", 0)
write("clr_n", 0)
write("d", 0)
print("Outputs LOW. Turn off the external logic rail before USB removal or rewiring.")
Complete host behavior tests: tests/test_events.py
import contextlib
import io
import json
from pathlib import Path
import subprocess
import sys
import unittest
CODE = Path(__file__).resolve().parents[1] / "code"
sys.path.insert(0, str(CODE))
from hc74_events import analyze_csv
from sequence import run, pad_fast_4ma
HEADER = "t_ms,d,clk,clr_n,q_observed,qbar_observed,kind,edge_qualification\n"
VALID = HEADER + (
"0,0,0,0,0,1,constructed,not_applicable\n"
"200,0,0,1,0,1,constructed,not_applicable\n"
"400,1,0,1,0,1,constructed,not_applicable\n"
"600,1,1,1,1,0,constructed,not_applicable\n"
"800,0,1,1,1,0,constructed,not_applicable\n"
"1000,0,0,1,1,0,constructed,not_applicable\n"
"1200,0,1,1,0,1,constructed,not_applicable\n"
"1400,0,0,1,0,1,constructed,not_applicable\n"
"1600,1,0,1,0,1,constructed,not_applicable\n"
"1800,1,1,1,1,0,constructed,not_applicable\n"
"2000,1,0,1,1,0,constructed,not_applicable\n"
"2200,1,0,0,0,1,constructed,not_applicable\n"
"2400,1,0,1,0,1,constructed,not_applicable\n"
"2600,1,1,1,1,0,constructed,not_applicable\n"
)
class LogicAndInputTests(unittest.TestCase):
def test_rising_edge_capture_high_clock_data_and_falling_edge_hold(self):
result = analyze_csv(VALID)
self.assertEqual([r.get("q_expected") for r in result.get("events", [])],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1])
def test_clear_without_clock_then_release_holds_until_new_rise(self):
events = analyze_csv(VALID).get("events", [])
self.assertEqual([(r.get("reason"), r.get("q_expected")) for r in events[11:14]],
[("async_clear", 0), ("release_hold", 0), ("rising_capture", 1)])
def test_constructed_match_is_not_physical_qualification(self):
result = analyze_csv(VALID)
self.assertEqual(result.get("summary", {}).get("matched"), 14)
self.assertEqual(result.get("physical_qualification_proven"), False)
def test_unqualified_measured_comparisons_withheld(self):
text = VALID.replace("constructed,not_applicable", "measured,unqualified")
result = analyze_csv(text)
self.assertEqual(result.get("summary", {}).get("withheld"), 14)
self.assertEqual([r.get("match") for r in result.get("events", [])], [None] * 14)
def test_declared_qualified_mismatch_kept_as_observation(self):
text = VALID.replace("constructed,not_applicable", "measured,declared_qualified")
text = text.replace("\n600,1,1,1,1,0", "\n600,1,1,1,0,0", 1)
result = analyze_csv(text)
self.assertEqual(result.get("summary", {}).get("mismatched"), 1)
self.assertEqual([r.get("observations_complementary") for r in result.get("events", [])[3:4]], [False])
def test_blank_observation_pair_allowed(self):
text = VALID.replace("0,0,0,0,0,1,constructed", "0,0,0,0,,,constructed", 1)
self.assertEqual(analyze_csv(text).get("summary", {}).get("without_observation"), 1)
def test_partial_observation_pair_refused(self):
with self.assertRaisesRegex(ValueError, "pair"):
analyze_csv(VALID.replace("0,0,0,0,0,1,constructed", "0,0,0,0,,1,constructed", 1))
def test_initial_state_must_be_explicit_reset(self):
with self.assertRaisesRegex(ValueError, "initial"):
analyze_csv(VALID.replace("0,0,0,0,0,1", "0,0,0,1,0,1", 1))
def test_too_short_guard_refused(self):
with self.assertRaisesRegex(ValueError, "200"):
analyze_csv(VALID.replace("200,0,0,1", "199,0,0,1", 1))
def test_duplicate_time_refused(self):
with self.assertRaisesRegex(ValueError, "200"):
analyze_csv(VALID.replace("200,0,0,1", "0,0,0,1", 1))
def test_multi_input_change_refused(self):
with self.assertRaisesRegex(ValueError, "one input"):
analyze_csv(VALID.replace("200,0,0,1", "200,1,0,1", 1))
def test_clear_transition_with_high_clock_refused(self):
with self.assertRaisesRegex(ValueError, "clock low"):
analyze_csv(HEADER + "0,0,0,0,0,1,constructed,not_applicable\n"
"200,0,1,0,0,1,constructed,not_applicable\n"
"400,0,1,1,0,1,constructed,not_applicable\n")
def test_invalid_binary_refused(self):
with self.assertRaisesRegex(ValueError, "binary"):
analyze_csv(VALID.replace("400,1,0,1", "400,true,0,1", 1))
def test_exponent_time_refused(self):
with self.assertRaisesRegex(ValueError, "integer"):
analyze_csv(VALID.replace("200,0,0,1", "2e2,0,0,1", 1))
def test_mixed_source_kind_refused(self):
with self.assertRaisesRegex(ValueError, "same"):
analyze_csv(VALID.replace("constructed,not_applicable", "measured,unqualified", 1))
def test_constructed_not_mislabelled_qualified(self):
with self.assertRaisesRegex(ValueError, "qualification"):
analyze_csv(VALID.replace("not_applicable", "declared_qualified"))
def test_wrong_or_duplicate_header_refused(self):
for header in [HEADER.replace("d,clk", "d,d"), HEADER.replace("t_ms", "time")]:
with self.subTest(header=header), self.assertRaisesRegex(ValueError, "header"):
analyze_csv(VALID.replace(HEADER, header))
def test_malformed_quoted_header_controlled(self):
with self.assertRaisesRegex(ValueError, "CSV"):
analyze_csv('"t_ms,d,clk\n')
def test_malformed_quoted_row_controlled(self):
with self.assertRaisesRegex(ValueError, "CSV"):
analyze_csv(HEADER + '"0,0,0,0\n')
def test_extra_columns_refused(self):
with self.assertRaisesRegex(ValueError, "columns"):
analyze_csv(VALID.replace("not_applicable\n", "not_applicable,extra\n", 1))
def test_empty_input_or_no_rows_refused(self):
for text in ["", HEADER]:
with self.subTest(text=text), self.assertRaises(ValueError):
analyze_csv(text)
def test_size_limit_refused(self):
with self.assertRaisesRegex(ValueError, "65536"):
analyze_csv("x" * 65537)
def test_cli_bad_header_exit2_no_json_or_traceback(self):
proc = subprocess.run([sys.executable, str(CODE / "hc74_events.py"), "-"],
input='"t_ms,d,clk\n', text=True, capture_output=True)
self.assertEqual((proc.returncode, proc.stdout, "Traceback" in proc.stderr), (2, "", False))
self.assertIn("Refused:", proc.stderr)
def test_cli_valid_json_exit0(self):
proc = subprocess.run([sys.executable, str(CODE / "hc74_events.py"), "-"],
input=VALID, text=True, capture_output=True)
self.assertEqual(proc.returncode, 0)
self.assertEqual(json.loads(proc.stdout).get("summary", {}).get("matched"), 14)
class PortableControllerTests(unittest.TestCase):
def test_pad_setting_preserves_every_unselected_bit(self):
for old in range(256):
new = pad_fast_4ma(old)
self.assertEqual(new & 0x31, 0x11)
self.assertEqual(new & ~0x31, old & ~0x31)
def test_final_capture_has_observation_prompt_before_cleanup(self):
state, prompts = {}, []
def observe(label):
prompts.append((label, dict(state)))
run(lambda k,v: state.__setitem__(k,v), lambda ms: None, observe, lambda *x: None)
self.assertEqual(len(prompts), 14)
self.assertEqual(prompts[-1][1], {"clk": 1, "d": 1, "clr_n": 1})
self.assertIn("final", prompts[-1][0].lower())
def test_sequence_safe_final_low_and_every_wait200(self):
writes, waits, reports = [], [], []
run(lambda k,v: writes.append((k,v)), waits.append, lambda label: None,
lambda *values: reports.append(values))
self.assertEqual(writes[-3:], [("clk",0),("clr_n",0),("d",0)])
self.assertEqual(waits, [200] * 13)
self.assertEqual(len(reports), 13)
def test_interruption_always_clears_clock_data(self):
writes = []
def stop(label):
raise KeyboardInterrupt()
with self.assertRaises(KeyboardInterrupt):
run(lambda k,v: writes.append((k,v)), lambda ms: None, stop, lambda *x: None)
self.assertEqual(writes[-3:], [("clk",0),("clr_n",0),("d",0)])
if __name__ == "__main__":
unittest.main()
The host evidence covers 28 test methods: rising capture, HIGH-clock/falling-edge hold, clear/release, observation provenance, noncomplementary observations, missing data, strict CSV including unterminated quoted headers, command-line refusal, and safe-low cleanup after a simulated interruption. The portable callbacks exercise the actual sequencing routine without importing hardware drivers. The adapter is supplied and statically inspected; that is not a MicroPython board run or target compilation.
Fault checks, challenge and answer
- Q seems to follow D continuously. Check exact part and pin numbers, whether you probed D instead of Q, and whether an apparent “HIGH” clock contains repeated crossings. A fast unknown clock does not become a transparent latch merely because a meter averages it.
- Q never captures HIGH. Verify PRE_N4 HIGH, clear actually inactive, both rails/references, the three buffer enable pins plus spare enable all LOW, and D/CLK amplitudes at the HC pins. A 3.3 V source bypassing U2 defeats the documented level budget.
- Clear release appears to change Q. Inspect clock transitions during release, wrong polarity, supply instability, insufficient recovery separation and probes. This protocol releases clear only with clock held LOW; it does not promise an arbitrary asynchronous release is safe.
- Unexpected supply current or a warm chip. Turn off. Check reversed package orientation, missing ground, output shorts, floating inputs and slow transitions. The 40 mA configuration is not proof of safe per-pin current.
- Both observed outputs match. Preserve that observation. Check mistaken probe points and the actual PRE/CLR wiring; do not force the record into complementary values. This recipe never qualifies the simultaneous-active condition.
Challenge. In the constructed sequence Q=1 after600 ms. D falls at800 ms while CLK stays HIGH, and CLK falls at1000 ms. What are Q and Q_N just before1200 ms, and immediately after its valid rising edge? Separately, why is removing the three input pulldowns or replacing U2 with a plain HC buffer not an equivalent “simplification”?
Answer
Just before1200 ms the stored bit remains Q=1,Q_N=0: neither changing D during HIGH clock nor the falling edge captures. The rising edge at1200 ms captures the then-LOW D, so after normal settling Q=0,Q_N=1. Input pulldowns define U2 inputs when the Pico is not driving; removing them can leave CMOS inputs floating. A plain HC buffer has different input thresholds and may not accept the Pico’s documented minimum HIGH. Neither change is justified by the ideal event model.
Files, related outcomes and primary references
Constructed CSV — reader ZIP; extract sn74hc74-edge-storage-reader/constructed-example.csv contains invented expected observations, not bench data. Blank physical CSV — reader ZIP; extract sn74hc74-edge-storage-reader/physical-blank.csv intentionally leaves actual inputs/observations empty and must be completed from a real qualified trial. Replace its illustrative coordinates with actual record coordinates while retaining the minimum-spacing protocol. Blank qualification sheet — reader ZIP; extract sn74hc74-edge-storage-reader/qualification-blank.csv keeps actual readings, instrument uncertainty and acceptance separate from the logical record. It is not pre-filled proof. Both original SVG/PNG pairs and all complete code/tests are in the reader.
Compare this edge-storage boundary with the existing SN74HC00 memory latch and the SN74HC165 parallel input snapshot. They teach different storage and capture behavior; their voltage/pin choices are not substitute instructions for this fixture.
- TI SN74HC74N ordering identity and SCLS094F datasheet, pin table and sections 6.3,6.5,6.7,8.4.
- TI SN74AHCT125N identity and SCLS264R datasheet, sections 4,5.2,5.4 and 5.5.
- TI Power-Up Behavior of Clocked Devices, SCHA005B; Implications of Slow or Floating CMOS Inputs, SCBA004E.
- Raspberry Pi RP2040 datasheet, current Release 13 electrical table and pad-control registers; official original Pico pinout; MicroPython 1.26.0 RP2 reference.
- Keysight34461A family datasheet, fixed10V input resistance; RIGOL official accessories/PVP2150 user guide, probe resistance, capacitance and compensation procedure; DHO800 user guide; MicroPython machine memory access and the pinned RP2 Pin implementation (value keyword; no drive/slew keywords used).
Verification boundary: this design was reviewed against the cited primary documents and its complete host behavior tests passed. Constructed examples remain separate from physical observations. No target firmware execution or physical waveform qualification is claimed.