When Code 8 Falls Below Code 7 in an R–2R Ladder

Change one resistor in a four-bit digital-to-analog converter (DAC) and the voltage can fall when the input number goes up. This passive DAC uses only resistors and an external voltage source. Its name, R–2R ladder, comes from the two resistance values: R along the ladder and twice that value on its branches.

A bit is a binary digit with value 0 or 1. At decimal 7 (0111 in binary), the three smaller bits are on. At decimal 8 (1000), they all turn off and the largest bit turns on. That bit rollover is the major carry. Compare the two voltages after they settle, then restore the original resistor and repeat. You can start with the offline practice. The voltages and graphs below are calculated. The bench procedure is for collecting your own readings.

Parts and settings

Use three 10 kiloohm (kΩ) resistors and five 20 kΩ resistors for the original ladder, plus a separate 30 kΩ resistor for the middle phase. A kiloohm is 1,000 ohms. Choose 1% resistors, where the tolerance is the permitted difference between the marked value and the actual resistance. Use a solderless breadboard or terminal fixture with identifiable rail and probe connections, and four insulated, individually removable selector leads.

Vishay MRS25 resistor options
ValueUseDerived order code
10 kΩR1–R3MRS25000C1002FCT00
20 kΩR4–R8 in A and CMRS25000C2002FCT00
30 kΩR4 replacement in BMRS25000C3002FCT00

MRS25 parts are axial, with one lead at each end. These options use 1% tolerance and a temperature coefficient of ±50 parts per million per kelvin (ppm/K). That coefficient describes how much resistance changes per degree of temperature change. The identifiers follow Vishay’s ordering table. The CT packaging code denotes fan-folded tape in a box, so verify the actual parts supplied when buying individual resistors.

Before assembly, select resistance mode on the Fluke 115 and identify each loose resistor with no external power or circuit attached. Compare the reading with the marked value, label the two R4 pieces, and keep the original 20 kΩ piece for phase C. Reading a resistor across an assembled ladder can include other paths through the circuit.

Wire the ladder from OUT to its termination

A node is a set of points joined by wire. The other supply node, G0, is the zero-volt return used for a 0. Connect G0 to the channel’s negative output. The supply’s protective-earth terminal has its own function and is left out of the ladder circuit.

Eight-resistor R–2R schematic with OUT at n0, code 8 selector wiring, independent VREF and G0 supply, and meter V and COM leads.
Voltage-mode ladder with code 8 shown. Four removable leads give D3 the positive rail and D2, D1 and D0 the return. The meter is shown reading OUT. Full-size schematic · Editable schematic
  1. Connect R1 from n0 to n1, R2 from n1 to n2 and R3 from n2 to n3. These three links are all 10 kΩ. The output test point OUT is n0, the end beside D3. VOUT is the voltage measured from OUT to G0.
  2. Connect R4 between n0 and D3, R5 between n1 and D2, R6 between n2 and D1, and R7 between n3 and D0. D3 is the most significant bit (MSB), with weight 8 in the input number. D0 is the least significant bit (LSB), with weight 1. Each D point remains accessible to the red probe.
  3. Place R8 between n3 and G0. This separate 20 kΩ resistor is the termination, the load at the far end needed to set the ladder ratios. It stays connected in every phase even when D0 is set to 0 and R7 also reaches G0.
  4. With the supply output off, connect the channel positive terminal to VREF and negative terminal to G0. Connect the meter’s COM lead to G0. Keep the red probe movable between the marked measurement points.
  5. For each bit, install one insulated removable lead from its D point to either VREF for 1 or G0 for 0. Use an exclusive one-lead connection. Bridging both rail sockets shorts the source. Leaving the bit open changes the branch and makes it invalid for a reading. Verify which breadboard holes actually share a conductor, including any breaks in the rail.

Collect A, B and C in that order

Four codes to set by hand
CodeD3D2D1D0
0G0G0G0G0
7G0VREFVREFVREF
8VREFG0G0G0
15VREFVREFVREFVREF

Make working copies of the blank observations worksheet and blank reference-check log. Both are comma-separated values (CSV) files. The worksheet expects the exact header below. All six voltage fields for a row use volts with a decimal point and no unit suffix, and the four b*_v columns are the voltages measured at D3 through D0, in order.

phase,code,vref_v,vout_v,b3_v,b2_v,b1_v,b0_v
  1. A, baseline. Fit the original 20 kΩ at R4. Use codes 0, 7, 8 and 15. Before changing any selector lead, resistor or fixture wiring, turn the supply output off and measure VREF against G0 to verify the rail has discharged. Set the next code with the output off, verify all four selectors, then enable the output.
  2. For each code. Verify CV and a reference between 4.45 V and 4.55 V. Wait until the display settles. Keep the code and wiring fixed and black COM secured at G0. Touch only the designated low-voltage test points with the insulated red voltage probe, avoiding contact across two points. Read the rail, read OUT, then read the rail again. Enter all three in the separate reference-check log. Use the immediately preceding VREF reading for vref_v and the matching OUT reading for vout_v. Measure and record D3 through D0 individually at the same fixed code. Repeat the group if reference drift, changing contacts or an unstable display makes it unsuitable. Retain original observations and the reasons for any redo. The paired reference readings can reveal drift between the checks. An excursion between those readings can escape detection.
  3. B, substitution. Turn the output off and confirm discharge. Put the 30 kΩ resistor in place of R4 only. Preserve the other resistors, supply, meter setup and contacts. Acquire the same four codes with the same checks.
  4. C, restoration. Again turn the output off and verify discharge before touching the wiring. Put the same original 20 kΩ resistor back at R4. Repeat all four codes and compare C with A. Shut off the output after the last reading.

Enter one row per phase and code, twelve rows total. The file may arrange rows in any order. The physical acquisition still goes A, B, then C. Keep unknown values blank in your working copy until you can complete the acquisition. Run the analyzer on an actually completed sheet.

Calculate what a single branch change does

In the nominal model, resistors have their marked values and the rails are ideal. A Thévenin equivalent represents a network at two terminals as one ideal voltage source and a series resistance. At n3, the two 20 kΩ legs combine to give 10 kΩ toward the two fixed rails, with equivalent voltage halfway between D0 and G0. Each step back toward n1 adds a 10 kΩ link, then combines the resulting 20 kΩ path equally with that node’s own 20 kΩ branch. At n1, this gives a 10 kΩ equivalent resistance and a voltage of l × VREF. To get l, divide the input code by 8, take the remainder and divide that remainder by 8. Equivalently, l = (code % 8) / 8, where % returns the remainder. Looking from OUT through R1 adds 10 kΩ to that source path, giving T = 20 kΩ.

At OUT, the lower-bit source is weighted by one over T. The D3 source is weighted by one over M, the value of R4. Let b3 = 0 or 1 denote D3. The unloaded fraction q = VOUT/VREF and the output resistance Rout, the resistance the meter sees when the ideal source voltages are set to zero, follow these equations.

q = (b3/M + l/T) / (1/M + 1/T)
Rout = M·T / (M + T)

With the original resistors in A and C, q = code/16 and Rout = 10 kΩ. In B, raising R4 to 30 kΩ reduces the influence of D3 and increases that of the lower-bit ladder. Rout becomes 12 kΩ. At 7 the three lower bits now hold OUT higher than D3 alone can at 8. The 50% change to R4 deliberately makes this contrast large. The usual 1% resistor tolerance alone gives no promise of this reversal.

Calculated unloaded ratios and voltages at VREF = 4.50 V
CodeA/C ratioA/C VB ratioB V
00000
77/161.9687521/402.3625
81/22.250002/51.8000
1515/164.2187537/404.1625

The unloaded 7→8 step is +VREF/16 (+0.28125 V) in A/C and −VREF/8 (−0.5625 V) in B. A meter with finite input resistance RL draws a small current. It scales the unloaded output ratio by RL / (RL + Rout). The Fluke manual lists a nominal DC-voltage input resistance greater than 10 megaohms (MΩ), where 1 MΩ is one million ohms. For illustration, 10 MΩ yields factors of about 0.999001 in A/C and 0.998801 in B. They illustrate loading for a fixed resistor model. Use your recorded voltages as read.

Reference current varies with code even though output resistance in this model is constant within each phase. With 4.55 V across the lowest possible 1%-low 10 kΩ resistor, the conservative power limit for any one resistor is 4.55²/9,900 Ω ≈ 2.10 milliwatts (mW). Vishay rates an MRS25 at 0.6 watts (W) under its specified mounting and temperature conditions. Four high branches each bounded using 19,800 Ω would draw less than 0.92 mA together, plus the small meter load, below the 20 mA limit. These estimates describe the correctly wired fixture. Check the supply indication on the assembled circuit.

Calculated nominal values for all 16 codes, with 0, 7, 8 and 15 marked. The phase B curve drops at 7 to 8 before and after endpoint mapping.
Calculated nominal unloaded values. Filled markers identify the four codes in the manual procedure. The connectors guide the eye between discrete codes. Full-size plot · Editable plot

Challenge: can adjusting both endpoints fix B?

Use each recorded ratio r(c) = VOUT/VREF as a point estimate, a value calculated from the two entered voltages. Try an endpoint mapping that assigns 0 to the code-0 ratio and 15 to the code-15 ratio. Will the resulting values at 7 and 8 be in increasing order? Predict the answer from the ratio table before opening the comparison.

Show the proof and phase B values

For a positive span s = r(15) − r(0), calculate z(c) = 15·[r(c) − r(0)] / s. This is a positive affine calibration, meaning it offsets the readings and scales them by a positive constant. Therefore z(8) − z(7) = (15/s)·[r(8) − r(7)]. Multiplication by that positive factor preserves the sign of the step. Nominal B gives z(7) = 315/37 ≈ 8.51 and z(8) = 240/37 ≈ 6.49. The endpoints agree by construction and the 7→8 step still falls.

Monotonicity means that a rising input code never decreases the output, and linearity describes how close the output is to a straight line versus code. A resolved negative step supplies a local counterexample to monotonicity. Four static codes cannot characterize all sixteen codes, establish voltage accuracy or capture switching glitches, the brief voltage disturbances during a transition.

Run the offline analyzer

Put ladder_step.py and your completed sheet in the same folder. Open a terminal there and use Python 3.9 or later. The program uses the standard library and reads files locally. Give your own completed file the name observations.csv for this command.

python3 ladder_step.py observations.csv --origin reported

Supply the origin as reported for entered readings from the bench. This is a declaration of where the values came from. With valid fixture values and no justified uncertainty bound, the reported command returns 3 and gives point estimates while leaving step signs pending.

To practice before building, use the separately labeled synthetic CSV and compare with the expected output. Synthetic means generated from the nominal equations. This example uses a constant 4.50 V reference and the unloaded model. Its illustrative 0.03 V bound applies to this example.

python3 ladder_step.py synthetic-practice.csv --origin synthetic --bound-v 0.03

Decide what your readings can resolve

The analyzer accepts an optional common absolute voltage-error bound U in volts using --bound-v U, where U stands for your justified numeric value. The bound says that the relevant true VREF and OUT each lie within the entered value plus or minus U. It needs to cover the complete applicable error, including the meter, temporal mismatch between sequential readings, contacts and settling. Reference-before and reference-after checks and CV indication offer evidence about the setup. They alone cannot exclude unobserved excursions or establish the full budget.

The Fluke 115’s stated DC accuracy on the 6.000 V range is ±(0.5% of reading + 2 counts) with a 0.001 V display increment, for one year after calibration at 18–28 °C and 0–90% relative humidity. Two counts contribute 0.002 V. At 4.55 V, this gives 0.02475 V for the meter component under those conditions. An allowance of 0.03 V would cover that meter component at 4.55 V. For reported readings, establish the actual conditions and the full applicable budget before supplying any bound. Omit it if that budget is unknown.

If the entire reference interval is positive, the analyzer divides both ends of the OUT interval by both ends of the VREF interval and retains the smallest and largest results. That covers all four endpoint combinations, including when an OUT interval includes values below zero. The local step can be anywhere between r8,low − r7,high and r8,high − r7,low. An interval strictly above zero resolves forward, one strictly below zero resolves reversed, and an interval touching or crossing zero leaves the sign unresolved. A positive bound whose reference interval reaches zero also leaves uncertainty pending. Reported input requires a positive bound if supplied. Synthetic mathematical inputs may use zero.

For restoration, compare A with C at each of the four codes. Their ratio intervals must share at least one value, including a shared endpoint, for the expected comparison. That is a consistency check after restoring R4. Its result is conditional on the input and bound.

Read the diagnostics in priority order

The program prints JavaScript Object Notation (JSON), a structured text format. Ratios and interval endpoints are exact fractions in strings. A null marks a result that was unavailable. The exit status is the number the program returns to the terminal. The first matching case below determines it.

  1. 2 · Malformed file or command. Correct the indicated field or command and run again. Use the exact header, one row per phase and code, finite numeric values and a valid origin and bound. Invalid data stops interpretation before phase calculations. --help prints ordinary usage text.
  2. 1 · Known fixture violation. VREF must be 4.45–4.55 V. Each bit reading must be within 0.05 V of its selected rail, and the bit and OUT readings must also lie between −0.05 V and VREF + 0.05 V. These are practical fixture screens, with measured voltages compared as entered. A nonpositive point endpoint span also fails. If a bit fails, inspect the code and lead continuity with the output off. An OUT outlier or failed span calls for rechecking the common return, voltage jack, R8 and the n0 probe position.
  3. 3 · Uncertainty pending. A complete bound is missing or the reference or step intervals cannot resolve the signs. Review drift, contacts and settling before attempting another group. Keep the pending result if the budget still lacks evidence.
  4. 1 · Resolved comparison differs. Check the wiring, R4 substitution and restoration. Compare the A/C results code by code for changes in meter range, reference or contacts. Preserve any unexpected sign or disjoint intervals.
  5. 0 · Expected conditional comparison. A and C resolve forward, B resolves reversed and the A/C ratio intervals overlap at each code under the declared bound. These facts describe the selected settled observations.

Code, worksheets and further reading

Get the complete Python analyzer, host tests, observations worksheet, reference log, synthetic practice CSV, synthetic expected result and reader instructions. The host tests check the model, parser and analysis. No physical test has been performed for this article.

Show the complete ladder_step.py listing
"""Analyze four static R–2R ladder codes in each of three manual phases."""

import argparse
import csv
import io
import json
import re
from decimal import Decimal, InvalidOperation
from fractions import Fraction
from typing import Optional


HEADER = ("phase", "code", "vref_v", "vout_v", "b3_v", "b2_v", "b1_v", "b0_v")
CODES = (0, 7, 8, 15)
MAX_BYTES = 64 * 1024
VREF_MIN, VREF_MAX = Fraction("4.45"), Fraction("4.55")
TOLERANCE = Fraction("0.05")
DECIMAL_TOKEN = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?")


def nominal_ratio(code: int, msb_ohms: int = 20000,
                  load_ohms: Optional[int] = None) -> Fraction:
    """Return the calculated VOUT/VREF for the specified R4 and optional load."""
    if code not in range(16) or msb_ohms <= 0 or (load_ohms is not None and load_ohms <= 0):
        raise ValueError("Need code 0–15 and positive resistances.")
    tail_ohms = 20000
    lower_bits = Fraction(code % 8, 8)
    msb = code // 8
    # The right-hand ladder seen through R1 is a 20 kΩ Thevenin source.
    ratio = (msb * tail_ohms + lower_bits * msb_ohms) / (msb_ohms + tail_ohms)
    if load_ohms is not None:
        output_ohms = Fraction(msb_ohms * tail_ohms, msb_ohms + tail_ohms)
        ratio *= load_ohms / (load_ohms + output_ohms)
    return ratio


def parse_decimal(token, location):
    if len(token) > 64 or not DECIMAL_TOKEN.fullmatch(token.strip()):
        raise ValueError(f"{location}: expected a finite decimal token of up to 64 characters.")
    try:
        number = Decimal(token)
    except InvalidOperation:
        raise ValueError(f"{location}: invalid decimal.") from None
    if not number.is_finite() or not -100 <= number.adjusted() <= 100:
        raise ValueError(f"{location}: expected decimal adjusted exponent from −100 to 100.")
    return Fraction(number)


def parse_rows(text):
    if len(text) > MAX_BYTES or len(text.encode("utf-8")) > MAX_BYTES:
        raise ValueError("CSV exceeds 64 KiB.")
    reader = csv.reader(io.StringIO(text, newline=""), strict=True)
    if tuple(next(reader, ())) != HEADER:
        raise ValueError("CSV header must be exactly " + ",".join(HEADER) + ".")

    rows = {}
    expected = {(phase, str(code)) for phase in "ABC" for code in CODES}
    for row in reader:
        if len(row) != len(HEADER):
            raise ValueError(f"CSV line {reader.line_num}: expected 8 columns.")
        phase, code = key = tuple(row[:2])
        if key not in expected:
            raise ValueError(f"CSV line {reader.line_num}: unexpected phase/code.")
        if key in rows:
            raise ValueError(f"CSV line {reader.line_num}: duplicate {phase}/{code}.")
        rows[key] = tuple(
            parse_decimal(token, f"{phase}/{code} {column}")
            for token, column in zip(row[2:], HEADER[2:])
        )
    if rows.keys() != expected:
        missing = ", ".join(f"{phase}/{code}" for phase, code in sorted(expected - rows.keys()))
        raise ValueError(f"CSV missing {missing}.")
    return rows


def check_fixture(phase, code, voltages, faults):
    vref, vout, *bits = voltages
    label = f"{phase}/{code}"
    if not VREF_MIN <= vref <= VREF_MAX:
        faults.append(f"{label} vref_v: outside 4.45–4.55 V.")
    if not -TOLERANCE <= vout <= vref + TOLERANCE:
        faults.append(f"{label} vout_v: outside fixture rails with 0.05 V allowance.")
    for bit, voltage in zip((3, 2, 1, 0), bits):
        expected = vref if code & (1 << bit) else 0
        if (not -TOLERANCE <= voltage <= vref + TOLERANCE
                or abs(voltage - expected) > TOLERANCE):
            faults.append(f"{label} b{bit}_v: outside expected rail with 0.05 V allowance.")


def ratio_interval(vref, vout, bound):
    reference = (vref - bound, vref + bound)
    if reference[0] <= 0:
        return None
    # Include all corners because an output interval can contain negatives.
    corners = [v / r for v in (vout - bound, vout + bound) for r in reference]
    return min(corners), max(corners)


def difference(later, earlier):
    if later is None or earlier is None:
        return None
    return later - earlier


def exact(value):
    return str(value) if value is not None else None


def exact_interval(interval):
    return [str(value) for value in interval] if interval is not None else None


def phase_facts(points, intervals, span):
    mapped = None
    if span is not None and span > 0:
        mapped = {
            str(code): exact(15 * (ratio - points[0]) / span) if ratio is not None else None
            for code, ratio in points.items()
        }

    step_interval = None
    sign = "unresolved"
    if intervals[7] is not None and intervals[8] is not None:
        low7, high7 = intervals[7]
        low8, high8 = intervals[8]
        step_interval = (low8 - high7, high8 - low7)
        if step_interval[0] > 0:
            sign = "forward"
        elif step_interval[1] < 0:
            sign = "reversed"

    return {
        "point_ratios": {str(code): exact(ratio) for code, ratio in points.items()},
        "ratio_intervals": {str(code): exact_interval(interval) for code, interval in intervals.items()},
        "local_step": {
            "point": exact(difference(points[8], points[7])),
            "interval": exact_interval(step_interval),
            "sign": sign,
        },
        "endpoint_mapping": {"span": exact(span), "points": mapped},
    }


def report(origin):
    return {
        "origin": origin,
        "hardware_tested": False,
        "bound_v": None,
        "assumptions": [
            "Origin is a declared label. CSV row order has no acquisition-time meaning.",
            "A supplied common absolute voltage-error bound is conditional on adequate same-code "
            "reference stability or a complete bound covering its variation. It must cover meter "
            "error, temporal/reference mismatch, contacts and settling as applicable.",
            "Results cover the entered four codes and settled 7→8 step in each phase.",
            "Ratios, mappings and interval endpoints are exact rational strings. Null marks an "
            "unavailable fact.",
        ],
        "reasons": [],
        "phases": {},
        "restoration": {},
    }


def finish(result, code, status, reasons):
    result.update(exit_code=code, status=status, reasons=reasons)
    return result


def analyze(text: str, origin: str, bound_v: Optional[str]) -> dict:
    """Return entry diagnostics, exact point facts and conditional comparisons."""
    result = report(origin)
    try:
        if origin not in ("synthetic", "reported"):
            raise ValueError("origin must be synthetic or reported.")
        bound = parse_decimal(bound_v, "bound_v") if bound_v is not None else None
        if bound is not None and (bound < 0 or (bound == 0 and origin == "reported")):
            raise ValueError("bound_v must be positive for reported input and nonnegative for synthetic input.")
        rows = parse_rows(text)
    except csv.Error as error:
        return finish(result, 2, "malformed", [f"Invalid CSV: {error}."])
    except ValueError as error:
        return finish(result, 2, "malformed", [str(error)])

    result["bound_v"] = exact(bound)
    fixture, pending, unexpected = [], [], []
    points, intervals = {}, {}
    if bound is None:
        pending.append("Supply a justified complete voltage-error bound to resolve step signs.")
    for phase in "ABC":
        phase_points, phase_intervals = {}, {}
        for code in CODES:
            voltages = rows[phase, str(code)]
            check_fixture(phase, code, voltages, fixture)
            vref, vout = voltages[:2]
            phase_points[code] = vout / vref if vref else None
            interval = ratio_interval(vref, vout, bound) if bound is not None else None
            phase_intervals[code] = interval
            if bound is not None and interval is None:
                pending.append(f"{phase}/{code} reference interval must be strictly positive.")
        points[phase], intervals[phase] = phase_points, phase_intervals
        span = difference(phase_points[15], phase_points[0])
        facts = phase_facts(phase_points, phase_intervals, span)
        if span is not None and span <= 0:
            fixture.append(f"{phase} endpoint point span must be positive.")
        sign = facts["local_step"]["sign"]
        if sign == "unresolved" and bound is not None:
            pending.append(f"{phase} local step is unresolved.")
        elif sign != "unresolved":
            expected_sign = "reversed" if phase == "B" else "forward"
            if sign != expected_sign:
                unexpected.append(f"{phase} local step is {sign}. Expected {expected_sign}.")
        result["phases"][phase] = facts

    restoration = {"c_minus_a": {}, "interval_overlap": {}}
    for code in CODES:
        label = str(code)
        restoration["c_minus_a"][label] = exact(difference(points["C"][code], points["A"][code]))
        a, c = intervals["A"][code], intervals["C"][code]
        overlap = max(a[0], c[0]) <= min(a[1], c[1]) if a is not None and c is not None else None
        restoration["interval_overlap"][label] = overlap
        if overlap is False:
            unexpected.append(f"A/C code {code} intervals are disjoint.")
    result["restoration"] = restoration

    reasons = fixture + pending + unexpected
    if fixture:
        return finish(result, 1, "fixture_violation", reasons)
    if pending:
        return finish(result, 3, "uncertainty_pending", reasons)
    if unexpected:
        return finish(result, 1, "unexpected_comparison", reasons)
    return finish(result, 0, "expected_conditional_comparison", [])


class ArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        raise ValueError(message)


def main(argv=None) -> int:
    parser = ArgumentParser(description=__doc__, allow_abbrev=False)
    parser.add_argument("file", metavar="FILE", help="completed observations CSV")
    parser.add_argument("--origin", choices=("synthetic", "reported"), required=True)
    parser.add_argument("--bound-v", metavar="U", help="justified complete absolute voltage-error bound")
    origin = None
    try:
        args = parser.parse_args(argv)
        origin = args.origin
        with open(args.file, "rb") as stream:
            data = stream.read(MAX_BYTES + 1)
        if len(data) > MAX_BYTES:
            raise ValueError("CSV exceeds 64 KiB.")
        result = analyze(data.decode("utf-8"), origin, args.bound_v)
    except OSError as error:
        result = finish(report(origin), 2, "malformed", [f"Cannot read CSV: {error}."])
    except UnicodeDecodeError:
        result = finish(report(origin), 2, "malformed", ["CSV must be UTF-8."])
    except ValueError as error:
        result = finish(report(origin), 2, "malformed", [str(error)])
    print(json.dumps(result, indent=2))
    return result["exit_code"]


if __name__ == "__main__":
    raise SystemExit(main())

Manufacturer references

Continue on Tricky Circuit