Integrated Circuits
Use four switches and a Texas Instruments SN74HCS138 to explore why two numbers can select the same output. Then change one connection so the circuit can tell the two cases apart.
An address is a number used to select a destination. Here the destination is an output testpoint, an accessible contact you can measure. A bit, short for binary digit, has a value of 0 or 1. We present four bits as a word. Written from left to right as W3 W2 W1 W0, they carry weights of 8, 4, 2 and 1. For example, 0010 means 2 and 1010 means 10.
A decoder is an integrated circuit (IC), a chip containing a circuit, that uses the input bits to select one output. The SN74HCS138 looks at three address inputs, A0, A1 and A2. An enable input controls whether the chip can select an output. This chip enables selection when G0 and G1 are LOW (near the 0 V return) and G2 is HIGH (near the positive supply). G0, G1 and the eight outputs Y0 through Y7 are active LOW. A low level asserts them, so the selected output goes LOW while the other seven stay HIGH. With selection disabled, all eight outputs are driven HIGH. Each has a push-pull driver that actively drives either level.
With W0, W1 and W2 wired to A0, A1 and A2, the selected output index is n = W0 + 2W1 + 4W2 whenever the chip is enabled. W3 is an external bit with no A3 pin on this chip. In the ignored phase, G0 stays LOW and W3 does not affect the decode. Addresses 2 and 10 both select Y2. Addresses 3 and 11 both select Y3. Each pair is an alias, two distinct addresses that select the same destination because the circuit overlooks their difference.
In the window phase, W3 drives G0. Words 0 through 7 have W3 = 0 and can still select an output. Words 8 through 15 have W3 = 1 and disable selection. This creates an address window, a range of addresses that can reach the decoder outputs.
The map is calculated for all 16 words in both phases. The experiment samples eight witnesses, individual phase-and-word cases chosen to test the two aliases and the effect of applying W3 to G0. No physical measurements are supplied. Even a complete set of eight reported trials only checks the selected cases.
Use the exact SN74HCS138DR in the 16-lead small-outline integrated circuit (SOIC) package, drawing D. It is a surface-mount chip. A passive carrier brings the soldered chip leads out to terminals that fit a breadboard, a board that joins inserted wires without solder. The carrier only changes access to the leads. Identify pin 1 from the chip marking and the Texas Instruments (TI) top-view drawing before soldering. Verify every terminal by electrical continuity, a check that two intended points are connected, with all power disconnected.
VCC labels the positive supply. GND is ground, the circuit’s 0 V return tied to the negative supply terminal. On this chip G0 is the active-low enable at pin 4. The return is GND at pin 8. Identical net labels in the drawing identify the same electrical connection. Each open testpoint circle is a place to touch the meter probe. All eight Y testpoints are electrically separate.
| Part | What it does |
|---|---|
| U1 and carrier | One TI SN74HCS138DR, SOIC(D) with 16 pins, fitted to a passive SOIC16-to-2.54 mm carrier matching the D-package drawing. Fit soldered headers for the breadboard. |
| R0–R3 | Four 4.70 kΩ, 1%, metal-film resistors rated at least 0.25 W each. These pull-ups connect the word nodes to VCC through resistance and give them a HIGH state when the switches are open. |
| S0–S3 | Four single-pole single-throw (SPST) dry contacts, each a switch that opens or closes one connection and supplies no voltage of its own. Each switch connects its W node to GND when closed. |
| C1 | One 100 nF ceramic capacitor rated at least 10 V. This bypass capacitor helps steady the chip’s local supply. Connect it close to pins 16 and 8 with short supply and return connections. |
| J1 | One labelled three-pin 2.54 mm header and one removable two-pin shunt, a conductive cap that joins the chosen pair of pins. |
| Wiring and testpoints | Breadboard, insulated leads and separate labelled contacts for VCC, W0–W3, G0/G1/G2 and Y0–Y7. Keep the eight output contacts separate and leave them unloaded except for the voltage probe when reading that point. |
| Supply | SIGLENT SPD3303X, independent channel 1 (CH1), set to 4.50 V and 0.020 A. Direct current (DC) here means a steady supply with fixed polarity. |
| Meter | Fluke 87V MAX digital multimeter (DMM), an instrument that displays electrical measurements. Use manual 6 V DC voltage mode. Connect the black common terminal (COM) to GND and use the red V/Ω socket for the voltage probe. |
| U1 pin | Name | Connection |
|---|---|---|
| 1 | A0 | W0 and TP_W0, with R0 to VCC and S0 to GND. |
| 2 | A1 | W1 and TP_W1, with R1 to VCC and S1 to GND. |
| 3 | A2 | W2 and TP_W2, with R2 to VCC and S2 to GND. |
| 4 | G0 | Active-low enable. J1.2 and TP_G0. |
| 5 | G1 | Active-low enable. GND and TP_G1. |
| 6 | G2 | Active-high enable. VCC and TP_G2. |
| 7 | Y7 | TP_Y7 only. |
| 8 | GND | CH1 negative, black meter COM, switch returns, J1.1 and C1 return. |
| 9 | Y6 | TP_Y6 only. |
| 10 | Y5 | TP_Y5 only. |
| 11 | Y4 | TP_Y4 only. |
| 12 | Y3 | TP_Y3 only. |
| 13 | Y2 | TP_Y2 only. |
| 14 | Y1 | TP_Y1 only. |
| 15 | Y0 | TP_Y0 only. |
| 16 | VCC | CH1 positive, TP_VCC, R0–R3, G2 and C1. |
Wire W3 to TP_W3 and J1.3, with R3 to VCC and S3 to GND. With any S switch open its corresponding W bit is 1. Close it for 0. The resistor stays between VCC and GND when the contact closes.
J1.1 is GND, J1.2 is the common pin connected to G0 and J1.3 is W3. Fit exactly one shunt. Bridge pins 1–2 for ignored and pins 2–3 for window. Switch CH1 off and verify VCC is below 0.10 V before changing a shunt or switch. Energize only after verifying the shunt spans the intended pair. Two shunts would tie W3 to ground, and an empty header would leave G0 floating, with no defined level.
4.50 V / 4700 Ω ≈ 0.957 mA through its pull-up. The resistor dissipates (4.50 V)² / 4700 Ω ≈ 4.31 mW. Four closed switches draw about 3.83 mA through their pull-ups.4 × 4.55 V / 4653 Ω ≈ 3.9115 mA. One resistor dissipates about 4.449 mW, well below its 0.25 W rating in this estimate.4.50 V × 10 MΩ / (10 MΩ + 4.70 kΩ) = 4.497886 V with those nominal values.±(0.00225 V + 0.001 V) = ±3.25 mV. This is an instrument specification calculation. Actual measurement uncertainty depends on the instrument and setup.These planning calculations use nominal meter resistance, with no minimum-impedance guarantee, and do not bound total supply current or board leakage. Use the specified meter profile, and keep light-emitting diodes or other devices off the outputs for this exercise.
TI recommends 2–6 V for VCC and 0 V through actual VCC at the inputs and outputs. A Schmitt-trigger input changes to HIGH at a different voltage than it changes to LOW. That gap is hysteresis. Inside it the result depends on the previous state. At TI’s specified 4.5 V test point, the rising threshold VT+ is 1.7–3.15 V and the falling threshold VT− is 0.9–2.2 V. These are test-point values for 4.5 V.
At 20 µA of output current, TI specifies VOH (HIGH output voltage) of at least VCC − 0.1 V and VOL (LOW output voltage) of at most 0.1 V. The separate 4.5 V, 6 mA test gives at least 4.0 V HIGH and at most 0.3 V LOW. The ±1 µA input leakage limit and 2 µA quiescent supply-current limit in the same table are tested at 6 V under stated conditions. Keep those 6 V limits at their stated test conditions when planning a 4.50 V circuit.
All inputs on this HCS part use Schmitt triggers and accept slow transitions. The 500 ns input transition limit for the different HC138 is specific to that part. Here we use only settled DC readings with every switch and shunt change made unpowered. Contact bounce can still cause repeated threshold crossings. No transition timing, bounce filtering, glitch-free switching or processor-bus performance is established by this exercise.
Use the blank worksheet, a comma-separated values (CSV) file with one field per column. Save your own copy before recording readings. Use the predicted states below to plan the test. Both phases expect G1 LOW and G2 HIGH.
| Phase | Word | W3–W0 | G0 | LOW output |
|---|---|---|---|---|
| ignored | 2 | 0010 | LOW | Y2 |
| ignored | 3 | 0011 | LOW | Y3 |
| ignored | 10 | 1010 | LOW | Y2 |
| ignored | 11 | 1011 | LOW | Y3 |
| window | 2 | 0010 | LOW | Y2 |
| window | 3 | 0011 | LOW | Y3 |
| window | 10 | 1010 | HIGH | None |
| window | 11 | 1011 | HIGH | None |
“None” means all eight outputs are HIGH. When one output is listed as LOW, the other seven are HIGH.
ignored, then the same four words in window. Before each word or shunt change, switch CH1 off and use the DMM in voltage mode to verify less than 0.10 V from VCC to GND. Set the four switches from the bit column and verify one shunt on the correct pair. Only use continuity with the source disconnected and the board unpowered, and restore voltage mode before enabling CH1.Each row takes 17 powered voltage readings, two for VCC, four word bits, three enables and eight outputs. The worksheet takes 136 powered readings across eight rows. Discharge, continuity, setup and repeats add work. These are sequential settled readings. They cannot reveal what the outputs did during a switch transition.
The standalone checker uses Python 3.9 or newer and its standard library. It writes analysis in JavaScript Object Notation (JSON), a structured text format for named values and lists. Run these commands from the folder containing decode_witness.py. The reader files include the tests, checker instructions and a constructed practice worksheet.
python3 decode_witness.py model
python3 decode_witness.py template > my-observations.csv
python3 decode_witness.py example > my-constructed-example.csv
python3 decode_witness.py check my-observations.csv
python3 decode_witness.py check constructed-example.csv
model generates all 32 calculated predictions as JSON, with eight output bits in Y0 to Y7 order. template and example generate CSV for the eight required pairs. The example has deliberately constructed rail readings and is labelled constructed on every row. check analyzes one worksheet supplied by you.
Preserve the exact header and all columns. Each phase and word pair must have a unique trial ID of 1–32 letters A–Z or a–z, digits, underscores or hyphens. Only word tokens 2, 3, 10 and 11 in either ignored or window are accepted. Row order is flexible. For your own readings use reported for record_kind and Fluke87VMAX_6VDC for meter_profile if that meter and range were used. Fill source_off_before_setup and switches_unchanged_during_scan with lowercase yes or no. Unknown readings, flags or metadata stay empty. A reported value is an operator statement.
Use UTF-8 text encoding with or without its leading byte-order mark, at most 1,048,576 bytes and at most eight records. Use fixed-point voltages in volts with digits and an optional sign and decimal point, up to nine digits after the point, 32 characters and magnitude at most 1000 V. The checker rejects scientific notation, nonfinite values, duplicate IDs and pairs, missing or surplus columns, blank lines and padded values. Blank fields contain no spaces. ID, phase and word must always be present.
Both VCC readings must be within 4.45–4.55 V inclusive and differ by at most 0.020 V. The terminal display domain is −0.020 V through the starting VCC reading plus 0.020 V. If starting VCC is missing, the upper bound is unavailable. Within the display domain, readings at or below 0.300 V qualify as LOW and readings at or above 4.200 V qualify as HIGH. Values between those limits are ambiguous. These are worksheet screens. Actual inputs and outputs still have to stay within 0 V and actual VCC.
constructed_witnesses_consistent or reported_witnesses_consistent, depending on the record kind. The report lists required and present pairs, qualified reported pairs, consistent constructed pairs, counts by record kind and each row’s reasons. Every analysis and model report sets physical_verified to false."""Calculate decoder states and check the eight-row static witness worksheet."""
import argparse
import csv
from decimal import Context, Decimal, localcontext
import io
import json
from pathlib import Path
import re
import sys
PHASES = ("ignored", "window")
WITNESS_WORDS = (2, 3, 10, 11)
WORD_TOKENS = {str(word): word for word in WITNESS_WORDS}
REQUIRED_PAIRS = tuple((phase, word) for phase in PHASES for word in WITNESS_WORDS)
METER_PROFILE = "Fluke87VMAX_6VDC"
SUPPLY_FIELDS = ("vcc_v", "vcc_end_v")
INPUT_FIELDS = ("w0_v", "w1_v", "w2_v", "w3_v", "g0_v", "g1_v", "g2_v")
OUTPUT_FIELDS = tuple(f"y{index}_v" for index in range(8))
SIGNAL_FIELDS = INPUT_FIELDS + OUTPUT_FIELDS
VOLTAGE_FIELDS = SUPPLY_FIELDS + SIGNAL_FIELDS
FLAG_FIELDS = ("source_off_before_setup", "switches_unchanged_during_scan")
HEADER = (
"trial_id", "record_kind", "meter_profile", "phase", "word",
*VOLTAGE_FIELDS, *FLAG_FIELDS,
)
ENUMS = {
"record_kind": ("", "constructed", "reported"),
"meter_profile": ("", METER_PROFILE),
**{field: ("", "yes", "no") for field in FLAG_FIELDS},
}
ID_PATTERN = re.compile(r"[A-Za-z0-9_-]{1,32}")
VOLTAGE_PATTERN = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]{0,9})?|\.[0-9]{1,9})")
MAX_BYTES = 1_048_576
MAX_MAGNITUDE = Decimal("1000")
SUPPLY_MIN = Decimal("4.45")
SUPPLY_MAX = Decimal("4.55")
MAX_DRIFT = Decimal("0.020")
DISPLAY_ALLOWANCE = Decimal("0.020")
LOW_MAX = Decimal("0.300")
HIGH_MIN = Decimal("4.200")
def _input_states(phase, word):
word_bits = tuple((word >> bit) & 1 for bit in range(4))
g0 = word_bits[3] if phase == "window" else 0
return (*word_bits, g0, 0, 1)
def expected_outputs(phase: str, word: int) -> tuple:
"""Return logic states in Y0..Y7 order for a calculated four-bit word."""
if phase not in PHASES:
raise ValueError("phase must be ignored or window")
if type(word) is not int or not 0 <= word <= 15:
raise ValueError("word must be an integer from 0 to 15")
*_, g0, g1, g2 = _input_states(phase, word)
enabled = (g0, g1, g2) == (0, 0, 1)
selected = word & 7
return tuple(int(not enabled or index != selected) for index in range(8))
def model_report() -> dict:
"""Return calculated predictions for both phases and all 16 words."""
return {
"scope": "calculated_model_only",
"physical_verified": False,
"predictions": [
{"phase": phase, "word": word, "outputs": list(expected_outputs(phase, word))}
for phase in PHASES
for word in range(16)
],
}
def _worksheet_csv(constructed):
buffer = io.StringIO(newline="")
writer = csv.writer(buffer, lineterminator="\n")
writer.writerow(HEADER)
for phase, word in REQUIRED_PAIRS:
trial_id = f"{phase}-{word}"
if constructed:
states = (*_input_states(phase, word), *expected_outputs(phase, word))
voltages = tuple("4.500" if state else "0.000" for state in states)
writer.writerow((
trial_id, "constructed", METER_PROFILE, phase, word,
"4.500", "4.500", *voltages, "yes", "yes",
))
else:
writer.writerow((trial_id, "", "", phase, word, *("" for _ in HEADER[5:])))
return buffer.getvalue()
def template_csv() -> str:
"""Return the eight required trials with only their identities filled."""
return _worksheet_csv(constructed=False)
def example_csv() -> str:
"""Return eight synthetic trials marked as constructed."""
return _worksheet_csv(constructed=True)
def _parse_voltage(text, field, location):
if text == "":
return None
if len(text) > 32 or not VOLTAGE_PATTERN.fullmatch(text):
raise ValueError(f"{location}: {field} must be fixed-point with up to 9 fractional places "
"and 32 characters")
value = Decimal(text)
if value.copy_abs() > MAX_MAGNITUDE:
raise ValueError(f"{location}: {field} magnitude exceeds 1000 V")
return value
def _parse_rows(data):
if len(data) > MAX_BYTES:
raise ValueError(f"worksheet exceeds {MAX_BYTES} bytes")
text = data.decode("utf-8-sig")
reader = csv.reader(io.StringIO(text, newline=""), strict=True)
if next(reader, None) != list(HEADER):
raise ValueError("worksheet header must match the template exactly")
rows = []
seen_ids = set()
seen_pairs = set()
for values in reader:
location = f"record {len(rows) + 1}"
if len(rows) == len(REQUIRED_PAIRS):
raise ValueError("worksheet contains more than eight records")
if len(values) != len(HEADER):
raise ValueError(f"{location}: expected {len(HEADER)} CSV fields")
row = dict(zip(HEADER, values))
trial_id = row["trial_id"]
if not ID_PATTERN.fullmatch(trial_id):
raise ValueError(f"{location}: invalid trial_id")
if trial_id in seen_ids:
raise ValueError(f"{location}: duplicate trial_id")
if row["phase"] not in PHASES or row["word"] not in WORD_TOKENS:
raise ValueError(f"{location}: unrecognized phase or word")
row["word"] = WORD_TOKENS[row["word"]]
pair = (row["phase"], row["word"])
if pair in seen_pairs:
raise ValueError(f"{location}: duplicate phase/word pair")
for field, allowed in ENUMS.items():
if row[field] not in allowed:
raise ValueError(f"{location}: invalid {field}")
for field in VOLTAGE_FIELDS:
row[field] = _parse_voltage(row[field], field, location)
seen_ids.add(trial_id)
seen_pairs.add(pair)
rows.append(row)
return rows
def _row_report(row):
reasons = []
def note(severity, field, message):
reasons.append({"severity": severity, "field": field, "message": message})
for field in ENUMS:
if row[field] == "":
note("pending", field, "Value is blank.")
elif field in FLAG_FIELDS and row[field] == "no":
note("mismatch", field, "Required procedure was reported as not followed.")
start, end = (row[field] for field in SUPPLY_FIELDS)
for field in SUPPLY_FIELDS:
value = row[field]
if value is None:
note("pending", field, "Voltage is blank.")
elif not SUPPLY_MIN <= value <= SUPPLY_MAX:
note("mismatch", field, "Supply is outside 4.45 to 4.55 V.")
if start is not None and end is not None and abs(start - end) > MAX_DRIFT:
note("mismatch", "vcc_end_v", "Start/end supply difference exceeds 0.020 V.")
upper_display = start + DISPLAY_ALLOWANCE if start is not None else None
states = {}
for field in SIGNAL_FIELDS:
value = row[field]
if value is None:
note("pending", field, "Voltage is blank.")
elif value < -DISPLAY_ALLOWANCE or (upper_display is not None and value > upper_display):
note("mismatch", field, "Voltage is outside the terminal display domain.")
elif value <= LOW_MAX:
states[field] = 0
elif value >= HIGH_MIN:
states[field] = 1
else:
note("pending", field, "Voltage lies between the LOW and HIGH screens.")
phase, word = row["phase"], row["word"]
inputs_match = True
for field, expected in zip(INPUT_FIELDS, _input_states(phase, word)):
observed = states.get(field)
if observed != expected:
inputs_match = False
if observed is not None:
note("mismatch", field, f"Expected logic {expected}, observed {observed}.")
if inputs_match:
for field, expected in zip(OUTPUT_FIELDS, expected_outputs(phase, word)):
observed = states.get(field)
if observed is not None and observed != expected:
note("mismatch", field, f"Expected logic {expected}, observed {observed}.")
else:
note("deferred", "outputs", "Output comparison requires known, correct word and enable states.")
severities = {reason["severity"] for reason in reasons}
if "mismatch" in severities:
status = "mismatch"
elif "pending" in severities:
status = "pending"
else:
status = "consistent"
return {
"trial_id": row["trial_id"],
"record_kind": row["record_kind"],
"phase": phase,
"word": word,
"status": status,
"reasons": reasons,
}
def _report(status, rows, errors):
by_pair = {(row["phase"], row["word"]): row for row in rows}
coverage = {
"required_pairs": [],
"present_pairs": [],
"qualified_reported_pairs": [],
"consistent_constructed_pairs": [],
"rows_by_kind": {"reported": 0, "constructed": 0, "unknown": 0},
}
for phase, word in REQUIRED_PAIRS:
pair = {"phase": phase, "word": word}
coverage["required_pairs"].append(pair)
row = by_pair.get((phase, word))
if row is None:
continue
coverage["present_pairs"].append(pair)
kind = row["record_kind"]
coverage["rows_by_kind"][kind or "unknown"] += 1
if row["status"] == "consistent":
if kind == "reported":
coverage["qualified_reported_pairs"].append(pair)
elif kind == "constructed":
coverage["consistent_constructed_pairs"].append(pair)
return {
"status": status,
"physical_verified": False,
"scope": "eight_static_witness_pairs",
"coverage": coverage,
"rows": rows,
"errors": errors,
}
def check_bytes(data: bytes) -> tuple:
"""Return the analysis report and exit code for one worksheet."""
try:
parsed = _parse_rows(data)
except (ValueError, csv.Error) as error:
return _report("invalid", [], [str(error)]), 2
# Voltage arithmetic stays exact even if a library caller changed precision.
with localcontext(Context(prec=28)):
rows = [_row_report(row) for row in parsed]
if any(row["status"] == "mismatch" for row in rows):
status, code = "mismatch", 1
elif len(rows) != len(REQUIRED_PAIRS) or any(row["status"] == "pending" for row in rows):
status, code = "pending", 3
else:
kinds = {row["record_kind"] for row in rows}
if len(kinds) != 1:
status, code = "pending", 3
else:
status, code = f"{rows[0]['record_kind']}_witnesses_consistent", 0
return _report(status, rows, []), code
def check_path(path) -> tuple:
"""Read at most one byte beyond the worksheet size limit."""
read_limit = MAX_BYTES + 1
data = bytearray()
try:
# Read without buffering so the underlying file offset obeys the cap.
with Path(path).open("rb", buffering=0) as worksheet:
while len(data) < read_limit:
chunk = worksheet.read(read_limit - len(data))
if not chunk:
break
data.extend(chunk)
except (OSError, ValueError) as error:
return _report("invalid", [], [f"Cannot read worksheet: {error}"]), 2
return check_bytes(bytes(data))
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
commands.add_parser("model", help="write 32 calculated predictions as JSON")
commands.add_parser("template", help="write the blank eight-trial CSV")
commands.add_parser("example", help="write the constructed eight-trial CSV")
check = commands.add_parser("check", help="check a worksheet and write JSON")
check.add_argument("file", metavar="FILE")
args = parser.parse_args(argv)
if args.command == "template":
sys.stdout.write(template_csv())
elif args.command == "example":
sys.stdout.write(example_csv())
elif args.command == "model":
print(json.dumps(model_report(), indent=2))
else:
report, code = check_path(args.file)
print(json.dumps(report, indent=2))
return code
return 0
if __name__ == "__main__":
sys.exit(main())
Which outputs should words 5 and 13 select in each phase? Identify the bit that changes, then confirm your answer with model.
5 is 0101 and 13 is 1101. Their lower three bits are 101, which gives index 5. In ignored, both select Y5. In window, 5 still selects Y5 and 13 makes all eight outputs HIGH because W3 raises G0. This is a calculated extension beyond the eight worksheet cases.
This partial address decode suits a settled logic demonstration with a voltage probe as the output load. An application that must make a unique selection for all 16 words needs to account for all four bits. Use a four-input decoder if its enable behavior, output levels, load and timing suit that application. For a live processor bus, also check the timing of address and enable changes and the behavior of the connected devices. For a switch that must produce just one event per press, use a separately qualified switch-bounce circuit.
For a related paper project, plan two eight-output banks. Draw a low-word bank enabled when W3 is 0 and a high-word bank enabled when W3 is 1. Label what words 2 and 10 would select in each bank. Each bank needs separate output nets.