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.
Digital logic · direct current (DC) experiment
An unlit light-emitting diode (LED) cannot tell you whether an output is driving LOW or has stopped driving. Use a weak pull-up and a restored HIGH control to investigate the difference on one channel of a TI SN74HC157N.
The SN74HC157 is a four-channel, two-to-one data selector. It chooses between two four-bit input words, A and B: a bit is a logical 0 or 1, and a word is an ordered group of bits. A shared select input chooses the word. It is not a decoder that turns a binary address into one selected output. Each output keeps its own channel: 1Y selects 1A or 1B, 2Y selects 2A or 2B, and so on.
The surprise is the input TI calls G, the active-low strobe or enable. When G is LOW (logic 0), selection works. When G is HIGH (logic 1), every Y output is driven LOW. This part has no high-impedance output-disable state. High impedance, often written Hi-Z, means an output offers only weak leakage rather than deliberately driving a logic level. That is not what disabling this device does.
Start with the three rules
| G | S | Each Y |
|---|---|---|
| 1 | X | 0, regardless of A or B |
| 0 | 0 | Corresponding A |
| 0 | 1 | Corresponding B |
Here S is the pin TI labels A/B: S=0 chooses A and S=1 chooses B. “Active-low enable” describes the level that permits selection; it does not promise a disconnected output at the other level. Read the function table for the exact part rather than inferring output behavior from a signal name.

logic.svgUse the exact package and define every input
The build is for Texas Instruments SN74HC157N, whose N package is a 16-pin plastic dual in-line package (PDIP). Put the notch at the top and view the body from above: pin 1 is upper left; numbering runs down the left side, then up the right side to pin 16. A different manufacturer or package needs its own pin verification.
| Pin | Signal | Fixture connection |
|---|---|---|
| 1 | S (A/B select) | 1 kΩ to G0; jumper to VCC |
| 2 | 1A | 1 kΩ to G0; jumper to VCC |
| 3 | 1B | 1 kΩ to G0; jumper to VCC |
| 4 | 1Y | Test point (TP) Y, meter and selected load |
| 5, 6 | 2A, 2B | G0 |
| 7 | 2Y | Leave unconnected |
| 8 | GND | G0 |
| 9 | 3Y | Leave unconnected |
| 10, 11 | 3B, 3A | G0 |
| 12 | 4Y | Leave unconnected |
| 13, 14 | 4B, 4A | G0 |
| 15 | G, active-low strobe | 1 kΩ to VCC; jumper to G0 |
| 16 | VCC | Regulated positive rail |
G0 is the single common return: the supply negative terminal, pin 8, meter common-return terminal (COM), all pull-down returns, and the LED cathode return. VCC is the single positive supply rail. Repeated VCC and G0 labels in the schematic refer to these same nets. Do not use the unused outputs as ground points or connect any output directly to a rail.
The current TI datasheet is SCLS113F, revised February 2025. Its pin-function TYPE column contains several inconsistent input/output (I/O) entries. The package top view, signal names, descriptions, functional diagram, and function table establish the roles used here; for example, 1Y is an output, not an input. The exercise also uses the actual HC electrical thresholds, not the datasheet’s generic TTL-compatible-input prose. Transistor-transistor logic (TTL) compatibility must not be assumed for this HC part.
Parts and instruments
| Item | Value / exact role |
|---|---|
| U1 | TI SN74HC157N, N / PDIP16 |
| R1–R4 | Four 1 kΩ ±1% resistors: S, 1A, 1B pull-downs and G pull-up |
| R5 | 2.2 kΩ ±1%, series LED resistor |
| R6 | 10 kΩ ±1%, optional Y pull-up |
| R7 | 10 kΩ ±1%, rail discharge bleeder |
| Resistor family | Vishay MRS25 metal film, or equivalent values with adequate documented rating; the chosen family is rated 0.6 W under its specified conditions |
| C1 | 100 nF ceramic, at least 16 V rating; directly between pins 16 and 8 with short leads |
| D1 | Vishay TLLR4400 low-current red 3 mm LED; verify its anode and cathode before fitting |
| Jumpers | Four 2-pin input headers/shunts; one 3-pin load header with only one shunt |
| Supply | SIGLENT SPD3303X, independent CH1 at 4.50 V, 40 mA current limit; other channels OFF, tracking OFF |
| Meter | Fluke 87V MAX, normal 6.000 V direct-current voltage range; red lead VΩ, black lead COM |
| Construction | Breadboard, short insulated jumpers, accessible VCC/G0/input/output test points |
Direct current is abbreviated DC; a light-emitting diode is an LED. The integrated circuit (IC) uses complementary metal-oxide-semiconductor (CMOS) logic. No microcontroller, signal generator, or oscilloscope is part of this fixture. Keep the bench supply’s protective earth intact. Do not connect an independent powered input source, another supply channel, or a USB-powered controller to the logic inputs.

circuit.svgBuild the two mutually exclusive output loads
For S, A, and B, an absent input shunt lets the 1 kΩ pull-down define 0; fitting the shunt connects that input to VCC and defines 1. G works the opposite way: its 1 kΩ pull-up gives an absent shunt a disabled 1; fitting its shunt connects G to G0 and enables selection. These are configuration jumpers, not powered switches.
Put 1Y on the middle pin 2 of J_LOAD. Pin 1 leads through R5, 2.2 kΩ, to the LED anode; the LED cathode bar returns to G0. Pin 3 leads through R6, 10 kΩ, to VCC. With the one load shunt on 1–2, Y feeds the LED branch. With it on 2–3, Y sees only the 10 kΩ pull-up and the meter: the entire LED branch is disconnected from Y. Never fit two load shunts.
Check LED polarity from its part identification and the Vishay outline, rather than relying on a trimmed lead length. An illuminated LED is a useful indication of HIGH, but lack of visible light is not a reliable voltage measurement. The meter is the logic-level witness. The TLLR4400 datasheet lists typical 1.9 V and maximum 2.4 V forward voltage at 2 mA; those figures do not guarantee brightness at the lower current this circuit may deliver.
Check the limits before power
TI recommends a 2–6 V supply for this part. The −0.5 to 7 V absolute supply rating is a stress boundary, not an operating target. This lesson stays near 4.50 V at room temperature. It makes no claim across the conflicting wide-temperature descriptions in the current product metadata and datasheet table.
At the datasheet’s 4.5 V test point, a valid input HIGH is at least 3.15 V and a valid LOW is at most 1.35 V. The jumpers choose the same VCC and G0 that power the IC, avoiding an unsupported promise that every 3.3 V controller output will work. Confirm the actual input rail voltages after each power-up; do not infer them solely from a shunt’s appearance.
The 4.5 V loaded-output row uses ±6 mA, not an unlimited output current rating. The conservative SN74 column gives HIGH at least 3.7 V and LOW at most 0.4 V under its stated test conditions. Our output loads are weaker than 6 mA. The program uses 3.7/0.4 V as chosen DC screening boundaries; its 4.45–4.55 V rail window is an engineering setup tolerance, not an extension or interpolation of TI’s 4.5 V guarantees.
Worst-case resistor values for these budgets: Rmin = 0.99 × nominal.
One closed input jumper: 4.55 V / 990 Ω = 4.60 mA; P ≈ 20.9 mW.
Four closed input jumpers: at most 18.4 mA from the supply.
LED branch, even with VF = 0: 4.55 V / 2178 Ω = 2.09 mA.
10 kΩ pull-up: at most 4.55 V / 9900 Ω = 0.460 mA.
10 kΩ rail bleeder: at most 0.460 mA, P ≈ 2.09 mW.
100 nF × 10 kΩ = 1 ms for that capacitor alone; not a PSU discharge time.
The zero-forward-voltage LED bound stays below the TLLR4400’s 7 mA absolute DC current limit, without pretending to know its actual forward voltage. The input pull currents come from the supply through the configuration resistors, not from the Y output. The 18.4 mA figure excludes the IC’s supply current, the bleeder, the selected load, and startup charging. SIGLENT specifies current-setting accuracy of ±(0.3% of the setting + 10 mA), so a 40 mA setting has a conservative lower value of 29.88 mA. The passive steady-load bound is about 20.94 mA before the IC’s own current and startup charging; a 30 mA setting could be as low as 19.91 mA and limit an otherwise correct fixture. The chosen 40 mA setting provides steady-load margin, but does not bound startup or make every breadboard fault harmless. It is not permission to short an output. If the supply enters current limit or VCC is outside the window, turn it OFF and inspect the wiring.
The meter’s nominal 10 MΩ voltage input draws about 0.45 µA at 4.5 V. A hypothetical disconnected node held up by 10 kΩ would be near 4.4955 V with that nominal meter resistance. That calculation is a comparison, not a measured output impedance or a specified leakage model. With G=1, a low Y despite the pull-up is consistent with active sinking. The enabled HIGH readings before and after it check that a permanent short to ground is not producing the same appearance.
Why every change is made with power OFF
The HC157 is not a Schmitt-trigger input device: it does not provide the distinct rising and falling switching thresholds used to tolerate a slowly changing signal. TI recommends input transition times no slower than 500 nanoseconds (ns) at 4.5 V. A hand-operated contact, breadboard capacitance, contact bounce, or an added resistor-capacitor (RC) debounce network—a circuit intended to remove repeated contact changes—does not establish compliance. Even smaller 1 kΩ defaults and short leads are not a measured edge guarantee.
This lesson therefore makes no independent input changes while the device is powered. All states are configured before power is applied. Supply and input rails still pass through startup, so the method does not certify startup behavior or transition-time compliance. It is restricted to settled DC observations after the supply and inputs have reached their rails. Do not use this arrangement to make claims about clean live switching, glitches, propagation delay, or clocked logic.
- OFF and discharge: turn CH1’s output OFF. Measure VCC relative to G0 in voltage mode. Wait until the actual reading supports VCC below 0.1 V; a displayed 0.090 V or less gives comfortable margin with the specified meter error. R7 provides a discharge path, but supply capacitance is unknown, so there is no fixed waiting-time guarantee. If VCC does not decay, stop and find the remaining source.
- Configure: only now move the four input shunts or J_LOAD. Check unused inputs remain at G0, unused outputs are open, IC orientation is correct, and the load shunt is exclusive.
- ON and verify: apply CH1 power. Check VCC is within 4.45–4.55 V, the supply is not current-limited, and S, A, B, and G actually read near their intended rail. A practical rail check is within 0.05 V of G0 for a selected LOW or within 0.05 V of VCC for a selected HIGH. Stop on an intermediate or wrong input.
- Settle and read: after stable DC readings, measure Y with the meter red lead at TP Y and COM at G0. Record the row’s off-VCC, on-VCC, and Y readings. These are separate measurements; the program cannot verify their sequence.
- OFF again: end the cycle with CH1 OFF. Repeat the discharge check before changing anything. Do not move a shunt “just once” while powered.
The meter leads stay in VΩ and COM. Never place a meter in its current range directly across VCC and G0, and do not use a resistance or continuity mode on a powered circuit. When checking an input, move only the insulated voltage probe; do not bridge adjacent IC pins with its tip.
First collect the 16 one-channel truth rows
Begin with J_LOAD on 1–2, LED mode. Use physical-blank.csv — reader ZIP; extract physical-blank.csv, whose first 16 rows specify the exact sequence below. Each row is its own complete power cycle. The file’s A and B mean 1A and 1B; the other channels remain physically tied to zero. The eight disabled rows deliberately vary both inputs and select while G remains 1.
| G | S | A | B | Y |
|---|---|---|---|---|
| 1 | 0 | 0 | 0 | 0 |
| 1 | 0 | 0 | 1 | 0 |
| 1 | 0 | 1 | 0 | 0 |
| 1 | 0 | 1 | 1 | 0 |
| 1 | 1 | 0 | 0 | 0 |
| 1 | 1 | 0 | 1 | 0 |
| 1 | 1 | 1 | 0 | 0 |
| 1 | 1 | 1 | 1 | 0 |
| 0 | 0 | 0 | 0 | 0 |
| 0 | 0 | 0 | 1 | 0 |
| 0 | 0 | 1 | 0 | 1 |
| 0 | 0 | 1 | 1 | 1 |
| 0 | 1 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 0 | 1 | 1 | 0 | 0 |
| 0 | 1 | 1 | 1 | 1 |
A reversed LED may stay dark even for a correct HIGH. A wrong select connection can make one part of the table seem right by coincidence. All 16 rows are useful because they exercise the chosen input, the unselected input, and disabled behavior independently. Do not keep testing a failing fixture: turn OFF, discharge, inspect, then repeat affected rows with a clear record of the repair.
Then distinguish LOW from disconnected
The LED truth rows alone do not establish the disabled output mode. For the optional stronger control, turn OFF, verify discharge, and move J_LOAD to 2–3 so the LED branch is disconnected and only the 10 kΩ pull-up remains. Keep S=0, A=1, B=1 throughout these three separate power cycles:
- G=0: enable selection and record a HIGH Y.
- G=1: disable selection and record a LOW Y despite the pull-up.
- G=0 again: record the restored HIGH Y.
Do not change G or the load while powered. A low middle reading with high readings on both sides is consistent with the datasheet’s active LOW output, rather than a permanently grounded Y. A high middle reading calls for checking the exact device, pin numbers, G connection, supply, and output path. A low reading in all three cycles suggests a short, missing supply, wrong wiring, or a failed device; it is not evidence of correct disable behavior.
The checker also requires the before/after HIGH readings to agree within a selected 0.1 V restoration budget including the meter’s stated reading-error bounds. This is a control against gross drift or a changed connection, not a statistical confidence interval. It is not an output-resistance measurement, a high-impedance leakage characterization, or a substitute for verifying the load wiring.
A complete four-channel model and a strict worksheet checker
The Python program below uses only the standard library. The model command enumerates all 1,024 combinations of G, S, the four A bits, and the four B bits. Its outputs are ideal logic values. This shows four-channel independence in the model; a one-channel physical fixture does not test all four physical output stages.
The check command reads a comma-separated values (CSV) worksheet. Keep its exact header and row order. Supply 16 LED rows, or those 16 followed by all three pull-up rows. The command requires an origin declaration: reported for readings a person reports, or constructed for invented demonstration values. That label is a declaration, not acquisition proof. The program has no instrument connection.
python3 hc157_selector.py model > ideal-four-channel.csv
python3 hc157_selector.py check constructed-example.csv --origin constructed
# Copy physical-blank.csv; enter your own readings, never the example values.
python3 hc157_selector.py check your-readings.csv --origin reported
python3 -m unittest -v test_hc157_selector
The Fluke 87V MAX normal 6.000 V DC specification used here is ±(0.05% of reading + 1 count), with 1 mV resolution. The cited accuracy conditions include two years after calibration, 18–28 °C, and the manual’s other applicable conditions. The code expands a reading v to v ± (0.0005|v| + 0.001 V). Do not treat this as a freshly calibrated uncertainty statement for your own meter. Substitute another instrument only after reviewing and adapting its range, input loading, accuracy, and code assumptions.
The complete interval must fit the chosen rail/logic screens. For example, a displayed 0.399 V has an upper bound slightly above 0.4 V, so it is unresolved rather than a passing LOW. Out-of-range finite voltages yield failed conditional screens; blank, nonnumeric, nonfinite, malformed, duplicated, or incomplete rows are input errors. The code does not reduce fixed error bounds by taking more readings.
A valid report returns exit status 0 even when its screens fail: inspect the JSON (JavaScript Object Notation) result’s booleans. Exit status 2 means malformed, incomplete, or unsupported input, with an error on standard error and no JSON result. If you omit the optional pull-up rows, their result is null, not an invented pass. The two acquisition-verification fields always remain false.
Complete program: hc157_selector.py
#!/usr/bin/env python3
"""SN74HC157 settled-DC teaching model and manual worksheet checker.
No instrument control, timing simulation or physical acquisition verification.
Exit0 is a valid conditional report; failed screens can remain. Exit2 means
malformed/incomplete input, stderr only and no JSON. Standard library only.
"""
import argparse
import csv
import io
import itertools
import json
import math
import sys
from pathlib import Path
FIELDS=('phase','step','g','s','a','b','off_vcc_v','vcc_v','y_v')
LOW=0.4
HIGH=3.7
EPS=1e-12
def quad(g, s, a, b):
def bit(v):
if type(v) is not int or v not in (0,1):
raise ValueError('logic values must be integer0 or1')
return v
bit(g); bit(s)
if not isinstance(a,(list,tuple)) or not isinstance(b,(list,tuple)) or len(a)!=4 or len(b)!=4:
raise ValueError('A and B must each contain four bits')
aa=tuple(bit(x) for x in a); bb=tuple(bit(x) for x in b)
return (0,0,0,0) if g else (bb if s else aa)
def expected_keys(pullup):
keys=[('led',str(i),*bits) for i,bits in enumerate(
itertools.product((1,0),(0,1),(0,1),(0,1)),1)]
if pullup:
keys += [('pullup',str(i),g,0,1,1)
for i,g in enumerate((0,1,0),1)]
return keys
def number(v):
if isinstance(v,bool):
raise ValueError('boolean is not a voltage')
try:
x=float(v)
except (ValueError,TypeError,OverflowError):
raise ValueError('blank or nonnumeric voltage')
if not math.isfinite(x):
raise ValueError('nonfinite voltage')
return x
def interval(v):
if abs(v)>6:
return None
error=.0005*abs(v)+.001
return [v-error,v+error]
def read_rows(path):
try:
with Path(path).open('rb') as f:
data=f.read(65537)
if len(data)>65536:
raise ValueError('worksheet exceeds65536 bytes')
parser=csv.reader(io.StringIO(data.decode('utf-8'),newline=''),strict=True)
header=next(parser,None)
if header!=list(FIELDS) or len(header)!=len(set(header)):
raise ValueError('need exact unique ordered header')
rows=[]
for cells in parser:
if len(cells)!=len(FIELDS):
raise ValueError('wrong field count or blank record')
rows.append(dict(zip(FIELDS,cells)))
if len(rows)>19:
raise ValueError('more than19 rows')
return rows
except (OSError,UnicodeError,csv.Error) as exc:
raise ValueError('cannot read strict UTF8 CSV: '+str(exc))
def analyze_rows(rows,origin):
if origin not in ('reported','constructed'):
raise ValueError('origin must be reported or constructed')
if not isinstance(rows,(list,tuple)) or len(rows) not in (16,19):
raise ValueError('need16 LED rows, optionally followed by3 pullup rows')
reports=[]
for row,key in zip(rows,expected_keys(len(rows)==19)):
if not isinstance(row,dict) or set(row)!=set(FIELDS):
raise ValueError('wrong worksheet fields')
if any(row[f] not in ('0','1') for f in ('g','s','a','b')):
raise ValueError('G,S,A,B cells must be literal0 or1')
bits=tuple(int(row[f]) for f in ('g','s','a','b'))
if (row['phase'],str(row['step']),*bits)!=key:
raise ValueError('wrong, duplicate or out-of-order acquisition key')
off,on,y=(number(row[f]) for f in ('off_vcc_v','vcc_v','y_v'))
oi,vi,yi=interval(off),interval(on),interval(y)
discharged=oi is not None and oi[0]>=-.01-EPS and oi[1]<=.1+EPS
rail=vi is not None and vi[0]>=4.45-EPS and vi[1]<=4.55+EPS
output_range=(yi is not None and vi is not None and
yi[0]>=-.05-EPS and yi[1]<=vi[1]+.05+EPS)
observed=None
if output_range:
if yi[1]<=LOW+EPS:
observed=0
elif yi[0]>=HIGH-EPS:
observed=1
g,s,a,b=bits
expected=quad(g,s,(a,0,0,0),(b,0,0,0))[0]
screens={'reported_discharge':discharged,'reported_on_rail':rail,
'output_range':output_range,'logic_matches':observed==expected}
reports.append({'phase':key[0],'step':key[1],'g':g,'s':s,'a':a,'b':b,
'off_vcc_v':off,'vcc_v':on,'y_v':y,'y_interval_v':yi,
'expected_bit':expected,'observed_bit':observed,
'matches_expected':observed==expected,'screens':screens,
'passed':all(screens.values())})
truth=all(r['passed'] for r in reports[:16])
pullup=restore_metric=None
if len(reports)==19:
before,disabled,restored=reports[16:]
if all(r['y_interval_v'] is not None for r in reports[16:]):
#Independent fixed meter errors; no sqrt(N) reduction.
restore_metric=(abs(before['y_v']-restored['y_v'])+
.0005*abs(before['y_v'])+.001+.0005*abs(restored['y_v'])+.001)
pullup=all(r['passed'] for r in reports[16:]) and restore_metric<=.1+EPS
else:
pullup=False
return {'schema':'trickycircuit-hc157-dc-1','valid_report':True,
'origin_declared':origin,'physical_acquisition_verified':False,
'power_cycles_input_rails_and_load_wiring_verified_by_software':False,
'truth_table_passed':truth,'pullup_control_passed':pullup,
'pullup_restore_metric_v':restore_metric,
'driven_low_observation_supported':None if pullup is None else truth and pullup,
'rows':reports,
'conditional_screens':{'nominal_VCC_v':4.5,'on_rail_interval_v':[4.45,4.55],
'off_VCC_interval_upper_v':.1,'LOW_interval_upper_v':LOW,
'HIGH_interval_lower_v':HIGH,'pullup_restore_limit_v':.1,
'voltage_error_v':'0.0005*abs(reading)+0.001; normal6V Fluke87V MAX',
'meter_conditions':'2 years after calibration,18–28C and applicable manual conditions',
'fixed_errors_reduced_by_repetition':False,'confidence_level':None},
'limits':['Chosen settledDC screens, not device certification or calibrated uncertainty.',
'State/origin/power-off readings are manual declarations, not acquisition proof.',
'No edge, delay, hazard, startup, output-impedance or high-impedance measurement.']}
def main(argv=None):
parser=argparse.ArgumentParser(description=__doc__)
sub=parser.add_subparsers(dest='command',required=True)
sub.add_parser('model',help='CSV of1024 constructed four-channel logic vectors')
check=sub.add_parser('check',help='check16 or19 manual worksheet rows')
check.add_argument('worksheet')
check.add_argument('--origin',required=True,choices=['reported','constructed'])
args=parser.parse_args(argv)
if args.command=='model':
writer=csv.writer(sys.stdout,lineterminator='\n')
writer.writerow(('origin','g','s','a1','a2','a3','a4','b1','b2','b3','b4','y1','y2','y3','y4'))
for bits in itertools.product((0,1),repeat=10):
g,s=bits[:2];a=bits[2:6];b=bits[6:10]
writer.writerow(('constructed_logic_model',*bits,*quad(g,s,a,b)))
return 0
try:
report=analyze_rows(read_rows(args.worksheet),args.origin)
output=json.dumps(report,indent=2,allow_nan=False)
except (ValueError,OSError,OverflowError) as exc:
print('input error: '+str(exc),file=sys.stderr)
return 2
print(output)
return 0
if __name__=='__main__':
sys.exit(main())
Constructed example: never a bench result
The following 19 rows deliberately use 4.500 V supply, 0.003 V after power-off, and 4.300/0.020 V for HIGH/LOW. They are arbitrary plausible demonstration values, not a transistor model, predicted analog output, instrument capture, or a suggested replacement for readings. Download the constructed CSV — reader ZIP; extract constructed-example.csv; download the empty measurement worksheet — reader ZIP; extract physical-blank.csv.
Complete constructed-example.csv
phase,step,g,s,a,b,off_vcc_v,vcc_v,y_v
led,1,1,0,0,0,0.003,4.500,0.020
led,2,1,0,0,1,0.003,4.500,0.020
led,3,1,0,1,0,0.003,4.500,0.020
led,4,1,0,1,1,0.003,4.500,0.020
led,5,1,1,0,0,0.003,4.500,0.020
led,6,1,1,0,1,0.003,4.500,0.020
led,7,1,1,1,0,0.003,4.500,0.020
led,8,1,1,1,1,0.003,4.500,0.020
led,9,0,0,0,0,0.003,4.500,0.020
led,10,0,0,0,1,0.003,4.500,0.020
led,11,0,0,1,0,0.003,4.500,4.300
led,12,0,0,1,1,0.003,4.500,4.300
led,13,0,1,0,0,0.003,4.500,0.020
led,14,0,1,0,1,0.003,4.500,4.300
led,15,0,1,1,0,0.003,4.500,0.020
led,16,0,1,1,1,0.003,4.500,4.300
pullup,1,0,0,1,1,0.003,4.500,4.300
pullup,2,1,0,1,1,0.003,4.500,0.020
pullup,3,0,0,1,1,0.003,4.500,4.300
Checks of the delivered code
The author ran the delivered CPython program’s 17 host test methods. They include comparison of all 1,024 vectors against a literal per-channel truth table, changing selected and unselected channels independently, strict worksheet coverage, power-off and rail failures, missing pull-up controls, restoration failure, interval-boundary decisions, extreme finite voltages, and actual command-line error/output behavior. Tests were developed through observed failing behavior and then passing implementations; a separate initial syntax-edit mistake is recorded in the author evidence and is not counted as a behavioral test.
These are tests of software on a host computer. They do not validate a breadboard, physical input rise/fall times, output voltage curves, probe placement, or any actual acquisition. The test source is complete below so readers can inspect what was tested and run the checks themselves.
Complete host tests: test_hc157_selector.py
import itertools
import unittest
import hc157_selector as h
# Literal per-channel truth table, ordered G,S,A,B. Independent of production code.
TABLE = {
(0,0,0,0):0,(0,0,0,1):0,(0,0,1,0):1,(0,0,1,1):1,
(0,1,0,0):0,(0,1,0,1):1,(0,1,1,0):0,(0,1,1,1):1,
(1,0,0,0):0,(1,0,0,1):0,(1,0,1,0):0,(1,0,1,1):0,
(1,1,0,0):0,(1,1,0,1):0,(1,1,1,0):0,(1,1,1,1):0}
class LogicTests(unittest.TestCase):
def test_all_four_channels_against_literal_truth_table(self):
count=0
for bits in itertools.product((0,1),repeat=10):
g,s=bits[:2];a=bits[2:6];b=bits[6:10]
want=tuple(TABLE[(g,s,a[i],b[i])] for i in range(4))
self.assertEqual(h.quad(g,s,a,b),want);count+=1
self.assertEqual(count,1024)
def test_selects_distinct_four_bit_words(self):
self.assertEqual(h.quad(0,0,(0,1,0,1),(1,0,1,0)),(0,1,0,1))
self.assertEqual(h.quad(0,1,(0,1,0,1),(1,0,1,0)),(1,0,1,0))
self.assertEqual(h.quad(1,1,(1,1,1,1),(1,1,1,1)),(0,0,0,0))
def test_channel_and_unselected_input_independence(self):
for select in (0,1):
for channel in range(4):
word=[0]*4;word[channel]=1
a,b=(word,[0]*4) if select==0 else ([0]*4,word)
self.assertEqual(h.quad(0,select,a,b),tuple(word))
a,b=([0]*4,word) if select==0 else (word,[0]*4)
self.assertEqual(h.quad(0,select,a,b),(0,0,0,0))
def test_rejects_nonbits_and_wrong_channel_count(self):
for value in (True,None,'0',2,-1,.5):
with self.assertRaises(ValueError):h.quad(value,0,[0]*4,[0]*4)
for word in ([],[0]*3,[0]*5,[0,0,0,True],'0000'):
with self.assertRaises(ValueError):h.quad(0,0,word,[0]*4)
import csv, io, json, subprocess, sys, tempfile
from pathlib import Path
FIELDS=('phase','step','g','s','a','b','off_vcc_v','vcc_v','y_v')
def fixture(pullup=True):
rows=[];values=[0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,1]
keys=list(itertools.product((1,0),(0,1),(0,1),(0,1)))
for i,((g,s,a,b),y) in enumerate(zip(keys,values),1):
rows.append(dict(zip(FIELDS,('led',str(i),str(g),str(s),str(a),str(b),'0.003','4.500','4.300' if y else '0.020'))))
if pullup:
for i,(g,y) in enumerate([(0,'4.300'),(1,'0.020'),(0,'4.300')],1):
rows.append(dict(zip(FIELDS,('pullup',str(i),str(g),'0','1','1','0.003','4.500',y))))
return rows
def sheet(rows):
out=io.StringIO(newline='');w=csv.DictWriter(out,fieldnames=FIELDS);w.writeheader();w.writerows(rows);return out.getvalue()
class WorksheetTests(unittest.TestCase):
def test_complete_truth_and_pullup_witness(self):
r=h.analyze_rows(fixture(),'reported')
self.assertTrue(r['valid_report']);self.assertTrue(r['truth_table_passed'])
self.assertTrue(r['pullup_control_passed']);self.assertTrue(r['driven_low_observation_supported'])
self.assertFalse(r['physical_acquisition_verified'])
def test_optional_witness_not_invented(self):
r=h.analyze_rows(fixture(False),'constructed')
self.assertTrue(r['truth_table_passed']);self.assertIsNone(r['pullup_control_passed'])
self.assertIsNone(r['driven_low_observation_supported'])
def test_wrong_truth_is_visible_failure(self):
rows=fixture();rows[10]['y_v']='0.020';r=h.analyze_rows(rows,'reported')
self.assertFalse(r['truth_table_passed']);self.assertFalse(r['rows'][10]['matches_expected'])
def test_poweroff_and_on_rail_controls(self):
for field,value in [('off_vcc_v','.2'),('vcc_v','4.600')]:
rows=fixture();rows[0][field]=value;r=h.analyze_rows(rows,'reported')
self.assertFalse(r['truth_table_passed']);self.assertFalse(r['driven_low_observation_supported'])
def test_pullup_low_and_restoration_are_required(self):
for i,value in [(17,'4.300'),(18,'4.050')]:
rows=fixture();rows[i]['y_v']=value;r=h.analyze_rows(rows,'reported')
self.assertTrue(r['truth_table_passed']);self.assertFalse(r['pullup_control_passed'])
def test_full_meter_interval_must_fit_logic_screen(self):
rows=fixture();rows[0]['y_v']='.399';r=h.analyze_rows(rows,'reported')
self.assertFalse(r['rows'][0]['matches_expected'])
rows[0]['y_v']='.398';self.assertTrue(h.analyze_rows(rows,'reported')['rows'][0]['matches_expected'])
def test_extreme_finite_voltage_valid_but_unsupported(self):
rows=fixture();rows[0]['y_v']='1e308';r=h.analyze_rows(rows,'reported')
self.assertTrue(r['valid_report']);self.assertFalse(r['truth_table_passed'])
self.assertIsNone(r['rows'][0]['y_interval_v']);json.dumps(r,allow_nan=False)
def test_out_of_range_pullup_cannot_overflow_report(self):
rows=fixture();rows[16]['y_v']='1e308';rows[18]['y_v']='-1e308'
r=h.analyze_rows(rows,'reported')
self.assertIsNone(r['pullup_restore_metric_v'])
self.assertFalse(r['pullup_control_passed']);json.dumps(r,allow_nan=False)
def test_strict_coverage_keys_and_numeric_cells(self):
for kind in ['duplicate','order','missing','extra','blank','nan','bits','origin']:
rows=fixture();origin='reported'
if kind=='duplicate':rows[1]=dict(rows[0])
if kind=='order':rows[0],rows[1]=rows[1],rows[0]
if kind=='missing':rows.pop()
if kind=='extra':rows.append(dict(rows[-1]))
if kind=='blank':rows[0]['y_v']=''
if kind=='nan':rows[0]['vcc_v']='nan'
if kind=='bits':rows[0]['g']='true'
if kind=='origin':origin='measured_by_software'
with self.subTest(kind=kind):
with self.assertRaises(ValueError):h.analyze_rows(rows,origin)
class ParserCLITests(unittest.TestCase):
def call(self,path,*args):
return subprocess.run([sys.executable,str(Path(h.__file__)),*args,str(path)],capture_output=True,text=True)
def test_actual_cli_good_and_failed_screen_exit_zero(self):
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'x.csv';p.write_text(sheet(fixture()))
r=self.call(p,'check','--origin','reported');self.assertEqual(r.returncode,0,r.stderr)
self.assertTrue(json.loads(r.stdout)['truth_table_passed'])
rows=fixture();rows[0]['off_vcc_v']='.2';p.write_text(sheet(rows))
r=self.call(p,'check','--origin','reported');self.assertEqual(r.returncode,0,r.stderr)
self.assertFalse(json.loads(r.stdout)['truth_table_passed'])
def test_actual_parser_failures_exit_two_without_json(self):
good=sheet(fixture())
bad=[good.replace('y_v','y_v,y_v',1),good.replace('0.003','nan',1),b'\xff',b' '*65537,
good.replace('0.003','OL',1),good.replace('0.003','\"0.003',1),good.replace('0.003','',1),good+'\n']
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'x.csv'
for value in bad:
p.write_bytes(value if isinstance(value,bytes) else value.encode())
r=self.call(p,'check','--origin','reported');self.assertEqual(r.returncode,2,(value[:80],r.stderr))
self.assertEqual(r.stdout,'')
def test_origin_is_mandatory_and_usage_is_not_result(self):
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'x.csv';p.write_text(sheet(fixture()))
r=self.call(p,'check');self.assertEqual(r.returncode,2);self.assertEqual(r.stdout,'')
def test_model_emits_all1024_labelled_vectors(self):
r=subprocess.run([sys.executable,str(Path(h.__file__)),'model'],capture_output=True,text=True)
self.assertEqual(r.returncode,0,r.stderr);rows=list(csv.DictReader(io.StringIO(r.stdout)))
self.assertEqual(len(rows),1024);self.assertEqual({x['origin'] for x in rows},{'constructed_logic_model'})
self.assertEqual([rows[-1][x] for x in ('y1','y2','y3','y4')],['0','0','0','0'])
if __name__=='__main__':unittest.main()
Challenge: would one more pull-up make an unlit LED conclusive?
Suppose G=1 and the LED is dark. You add the 10 kΩ pull-up but leave the LED connected. Y still reads low. Have you distinguished active LOW from a disconnected output? What should be changed, and which control checks a permanent short?
Reveal the answer
No. The LED branch is another path to ground and can load a hypothetical disconnected node, so the intended comparison is compromised. With power OFF and VCC verified discharged, select only the 10 kΩ pull-up branch and electrically disconnect the entire LED branch from Y. Then perform enabled HIGH, disabled LOW, and enabled HIGH again as three separate power cycles. A low middle result bracketed by HIGH results is consistent with active sinking and checks against a permanent ground short. It still does not quantify output impedance, measure Hi-Z leakage, or prove that the recorded wiring and sequence occurred.
Sources and further reading
Primary documents were accessed on 29 November 2026. The device review found no separate current TI errata document on the inspected family/part resources and official search; that is a bounded search result, not a claim that errata can never exist. Recheck the exact part and document revision before adapting this circuit.
- TI SN54HC157 / SN74HC157 datasheet, SCLS113F, revised February 2025: package top view, function table, recommended conditions, electrical characteristics and layout advice.
- TI SN74HC157N exact-part page: N / PDIP16 identity; active status is not a stock or orderability claim.
- Vishay TLL.440. LED family, document 83029, revision 2.7, 5 July 2022: exact TLLR4400 ratings and package polarity.
- Vishay MRS16 / MRS25 resistor data: resistance tolerance and rated-power conditions.
- Fluke 87V MAX Users Manual, October 2019, revision 1, February 2020: voltage range, input impedance and accuracy conditions.
- SIGLENT SPD3303X manufacturer specifications: current-setting resolution and accuracy used in the load-margin calculation.
- SIGLENT SPD3303X quick start, EN02A: independent-channel setup and normal operation.
For a different input problem, see SN74HC14: debounce a button and measure hysteresis. For a different meaning of active-low logic and an idle code, see SN74HC148: distinguish idle from request zero. Neither device’s behavior should be substituted for this selector’s function table.
Download the reader ZIP and extract it first. Open preview.html for the local reading layout. The ZIP contains this complete article, original editable figures, Python program and tests, worksheets, and source notes. Manufacturer PDFs remain linked to their publishers and are not redistributed.


