---
title: "Lab: instrument data, text and bits"
heading: Commands out, readings and raw bytes back
eyebrow: A4 · Lesson 5 · Lab: instrument data, text and bits
xp: 60
---

::: hook
Every automated bench runs the same loop: send an instrument a line of text, get a line of text or a block of raw bytes back, and turn it into numbers you can trust. Lessons 1 to 4 gave you the pieces: functions, floats and their rounding, strings and formatting, and bits and bytes. This lab puts them together on the kinds of data a real bench produces, a meter's comma-separated readings, a 24-bit converter's raw samples, a status word, and a table of results someone else has to read.
:::

::: predict
## A 24-bit converter sends the three bytes 0xFF, 0xF0, 0x00, most significant first, in two's complement. Is the reading positive or negative?

- [x] Negative, because the top bit of the first byte is set
- [ ] Positive, because every byte is a positive number
- [ ] Zero, because the last byte is zero
- [ ] You can't tell without the reference voltage

::: reveal
Negative. In two's complement the top bit of the whole value is the sign, and 0xFF has its top bit set. As an unsigned number the three bytes are 16 773 120; subtracting $2^{24}$ gives −4096. The reference voltage sets how many volts a count is worth, but not the sign.
:::
:::

::: nameit
## The workflow

1. **Build the command** with an f-string, fixing the number of decimals the instrument expects: `f"SOUR:VOLT {v:.3f}"`.
2. **Split the reply** on its separator and convert each piece: `[float(s) for s in reply.split(",")]`. `float` reads `E` notation directly.
3. **Decode raw bytes** with `int.from_bytes(b, "big")`, then fix the sign for two's complement: subtract $2^{n}$ when the top bit of an $n$-bit value is set.
4. **Scale counts to units.** A bipolar $n$-bit converter with reference $V_{ref}$ is worth $V_{ref}/2^{n-1}$ volts per count.
5. **Format the results** for a person: a fixed width per column, a sensible number of significant figures, and units.

Test each step on a value whose answer you already know, a datasheet's example or a hand calculation, before trusting it on real data.
:::

::: example
## A meter returns `+1.00012E+00,+9.99870E-01,+1.00031E+00,+9.99650E-01`. Find the mean and the largest deviation from it.

::: solution
1. **Parse the reply and compute.** Split at the commas, convert each piece with `float`, then take the mean and the largest distance from it.

```python
reply = "+1.00012E+00,+9.99870E-01,+1.00031E+00,+9.99650E-01"
x = [float(s) for s in reply.split(",")]
m = sum(x) / len(x)
dev = max(abs(v - m) for v in x)
print(f"{m:.6f} V, worst {dev * 1e6:.0f} µV")    # 0.999988 V, worst 337 µV
```

2. **Read the mean.** It is 0.9999875 V.
3. **Find the worst reading.** The reading farthest from the mean, 0.99965 V, is 337.5 µV away:
   $$\begin{aligned} \Delta &= 0.9999875 - 0.99965\ \text{V} \\ &= 337.5\ \mu\text{V} \end{aligned}$$
4. **Choose the format.** Printing the deviation in microvolts with no decimals says what matters without six meaningless digits.

**Answer:** the mean is 0.9999875 V, and the largest deviation from it is 337.5 µV.
:::
:::

::: example
## A 24-bit bipolar converter with a 2.048 V reference sends 0x40 0x00 0x00, then 0x80 0x00 0x00. What voltages are these?

::: solution
1. **Decode the bytes as two's complement.** Join them big-endian, subtract $2^{24}$ when the top bit is set, and scale by $V_{ref}/2^{23}$.

```python
def volts(b, vref=2.048):
    raw = int.from_bytes(b, "big")
    if raw >= 1 << 23:
        raw -= 1 << 24
    return raw * vref / (1 << 23)

print(volts(bytes([0x40, 0x00, 0x00])))   # 1.024
print(volts(bytes([0x80, 0x00, 0x00])))   # -2.048
```

2. **The first code.** 0x400000 is $2^{22}$, half of $2^{23}$, so it's half the reference:
   $$\begin{aligned} V &= \tfrac{1}{2} \times 2.048\ \text{V} \\ &= 1.024\ \text{V} \end{aligned}$$
3. **The second code.** 0x800000 has the top bit set; minus $2^{24}$ it's $-2^{23}$, the most negative code, which is exactly −2.048 V.
4. **The other end of the range.** The most positive code, 0x7FFFFF, is one count short of +2.048 V: a two's complement range is lopsided by one.

**Answer:** 0x40 0x00 0x00 is 1.024 V, and 0x80 0x00 0x00 is −2.048 V.
:::
:::

::: check
kind: python
given: k = 0..3 int

## A meter answers a "read all" query with comma-separated readings in E notation. Write `stats(reply)` returning `(mean, pk2pk)`, the mean and the largest minus the smallest reading. Then set `s = stats(reply)` for the reply the starter picks.

```python starter
replies = ["+1.00012E+00,+9.99870E-01,+1.00031E+00,+9.99650E-01",
           "-2.50010E-03,-2.49980E-03,-2.50050E-03",
           "+4.99987E+00,+5.00021E+00,+5.00003E+00,+4.99995E+00,+5.00009E+00",
           "+1.20000E+01"]
reply = replies[k]

def stats(reply):
    return 0, 0

s = stats(reply)
print(s)
```

```python solution
replies = ["+1.00012E+00,+9.99870E-01,+1.00031E+00,+9.99650E-01",
           "-2.50010E-03,-2.49980E-03,-2.50050E-03",
           "+4.99987E+00,+5.00021E+00,+5.00003E+00,+4.99995E+00,+5.00009E+00",
           "+1.20000E+01"]
reply = replies[k]

def stats(reply):
    x = [float(v) for v in reply.strip().split(",")]
    return sum(x) / len(x), max(x) - min(x)

s = stats(reply)
print(s)
```

```python tests
xs = [float(v) for v in reply.split(",")]
assert abs(s[0] - sum(xs) / len(xs)) < 1e-12 * max(1, abs(s[0])), f"The mean should be {sum(xs) / len(xs):.7g}."
assert abs(s[1] - (max(xs) - min(xs))) < 1e-15 + 1e-12 * abs(s[1]), f"The peak-to-peak should be {max(xs) - min(xs):.4g}."
assert stats("+1.0E+00,+3.0E+00\n") == (2.0, 2.0), "Strip the line ending before splitting."
```

::: right
Right. One reading gives a peak-to-peak of zero, and a stray newline at the end of a reply is stripped before splitting, both cases a real bench hits.
:::
:::

::: check
kind: python
given: k = 0..4 int

## Write `volts(b, vref=2.048)` for a 24-bit bipolar converter: three bytes, most significant first, two's complement, $V_{ref}/2^{23}$ volts per count. Then set `v` for the bytes the starter picks.

```python starter
frames = [bytes([0x40, 0x00, 0x00]), bytes([0x80, 0x00, 0x00]), bytes([0xFF, 0xF0, 0x00]), bytes([0x12, 0x34, 0x56]), bytes([0x7F, 0xFF, 0xFF])]
b = frames[k]

def volts(b, vref=2.048):
    return int.from_bytes(b, "big") * vref / (1 << 24)

v = volts(b)
print(v)
```

```python solution
frames = [bytes([0x40, 0x00, 0x00]), bytes([0x80, 0x00, 0x00]), bytes([0xFF, 0xF0, 0x00]), bytes([0x12, 0x34, 0x56]), bytes([0x7F, 0xFF, 0xFF])]
b = frames[k]

def volts(b, vref=2.048):
    raw = int.from_bytes(b, "big")
    if raw >= 1 << 23:
        raw -= 1 << 24
    return raw * vref / (1 << 23)

v = volts(b)
print(v)
```

```python tests
raw = int.from_bytes(b, "big", signed=True)
want = raw * 2.048 / 2**23
assert abs(v - want) < 1e-15, f"These bytes are {raw} counts, {want:.9g} V."
assert abs(volts(bytes([0x40, 0, 0]), vref=2.5) - 1.25) < 1e-15, "Use the vref argument: 0x400000 with a 2.5 V reference is 1.25 V."
```

::: right
Right. 0xFFF000 is −4096 counts, −1.000 mV, and 0x7FFFFF is 2.047 999 756 V, one count below the reference. Checking the extreme codes catches most decoding bugs.
:::
:::

::: check
kind: python
given: v = 0.5 | 1.25 | 3.3 | 12; i = 0.01 | 0.1 | 0.5 | 1.5

## A bench supply takes the commands `VOLT <v>` and `CURR <i>`, with the voltage to 3 decimals and the current to 4, then `OUTP ON`. Write `setup(v, i)` returning the three commands as one string separated by `"\n"`. Then set `cmd = setup(v, i)` for `v` = {v} and `i` = {i}.

```python starter
def setup(v, i):
    return f"VOLT {v}\nCURR {i}\nOUTP ON"

cmd = setup(v, i)
print(cmd)
```

```python solution
def setup(v, i):
    return f"VOLT {v:.3f}\nCURR {i:.4f}\nOUTP ON"

cmd = setup(v, i)
print(cmd)
```

```python tests
want = f"VOLT {v:.3f}\nCURR {i:.4f}\nOUTP ON"
assert cmd == want, f"cmd should be {want!r}."
assert setup(5, 0.1) == "VOLT 5.000\nCURR 0.1000\nOUTP ON", "Format with .3f and .4f so the instrument always gets the same number of decimals."
```

::: right
Right. A fixed number of decimals makes every command the same shape, which is easier for the instrument's parser and for you when you read a log of what was sent.
:::
:::

::: check
kind: python
given: ch = 0..15 int; gain = 0..7 int; start = 0 | 1

## A converter's control register takes the channel in bits 0 to 3, a gain code in bits 4 to 6, and a start flag in bit 15. Write `control(ch, gain, start)` returning the register value, and `decode(reg)` returning `(ch, gain, start)` back from it. Set `reg = control(ch, gain, start)` for `ch` = {ch}, `gain` = {gain} and `start` = {start}, and `back = decode(reg)`.

```python starter
def control(ch, gain, start):
    return ch + gain + start

def decode(reg):
    return (0, 0, 0)

reg = control(ch, gain, start)
back = decode(reg)
print(hex(reg), back)
```

```python solution
def control(ch, gain, start):
    return (ch & 0xF) | ((gain & 0x7) << 4) | ((start & 1) << 15)

def decode(reg):
    return (reg & 0xF, (reg >> 4) & 0x7, (reg >> 15) & 1)

reg = control(ch, gain, start)
back = decode(reg)
print(hex(reg), back)
```

```python tests
want = ch | (gain << 4) | (start << 15)
assert reg == want, f"reg should be {hex(want)}: OR each field into place after shifting it."
assert back == (ch, gain, start), "decode should undo control: shift each field down and mask it."
assert decode(control(15, 7, 1)) == (15, 7, 1) and control(15, 7, 1) == 0x807F, "With every field at its maximum the register is 0x807F."
```

::: right
Right. Packing shifts each field up and ORs it in; unpacking shifts it down and masks it off. Testing the round trip, `decode(control(...))`, at the extreme values catches a wrong shift or mask straight away.
:::
:::

::: check
kind: python
given: k = 0..2 int

## Write `table(rows)` that formats a list of `(name, value, unit)` rows as text, one row per line: the name left-aligned in 8 characters, the value right-aligned in 10 characters with 4 significant figures (`.4g`), a space, then the unit. Set `text = table(rows)` for the rows the starter picks.

```python starter
sets = [[("Vout", 3.29871, "V"), ("Iq", 0.000412, "A"), ("f", 1000.3, "Hz")],
        [("R1", 4712.4, "Ω"), ("R2", 10003.9, "Ω")],
        [("gain", 19.9873, "dB"), ("phase", -44.812, "°"), ("fc", 15912.0, "Hz"), ("Q", 0.70711, "")]]
rows = sets[k]

def table(rows):
    return "\n".join(f"{n} {v} {u}" for n, v, u in rows)

text = table(rows)
print(text)
```

```python solution
sets = [[("Vout", 3.29871, "V"), ("Iq", 0.000412, "A"), ("f", 1000.3, "Hz")],
        [("R1", 4712.4, "Ω"), ("R2", 10003.9, "Ω")],
        [("gain", 19.9873, "dB"), ("phase", -44.812, "°"), ("fc", 15912.0, "Hz"), ("Q", 0.70711, "")]]
rows = sets[k]

def table(rows):
    return "\n".join(f"{n:<8}{v:>10.4g} {u}" for n, v, u in rows)

text = table(rows)
print(text)
```

```python tests
want = "\n".join(f"{n:<8}{v:>10.4g} {u}" for n, v, u in rows)
assert text == want, "Each line is f'{name:<8}{value:>10.4g} {unit}', joined with newlines."
assert table([("x", 1234567, "V")]) == "x" + " " * 8 + "1.235e+06 V", "A large value in .4g switches to E notation and is still right-aligned in 10 characters."
```

::: right
Right. `<8` and `>10` fix the column widths, so the values line up whatever their size, and `.4g` keeps four significant figures in or out of E notation.
:::
:::

::: check
given: n = 12 | 16 | 18 | 24; vref = 1.25 | 2.048 | 2.5
answer: vref/2^(n - 1)
unit: V
tolerance: 0.5%

## A bipolar {n}-bit converter covers −{vref} V to +{vref} V. How many volts is one count?

::: right
Right. A bipolar converter uses one bit for the sign, so $2^{\given{n} - 1}$ counts span the reference: {answer} per count.
:::

::: misses
- [vref/2^n] That spreads the reference over every code. Half the codes are negative, so $2^{\given{n} - 1}$ counts span 0 to +{vref} V.
- [2*vref/2^(n - 1)] That's two counts' worth. The full span is $2V_{ref}$ over $2^{\given{n}}$ codes, which is $V_{ref}/2^{\given{n} - 1}$.
- [any] Not yet. Divide the reference by the number of positive codes, $2^{\given{n} - 1}$.
:::
:::

::: explain
## Why should you test a decoder on the extreme codes, like 0x800000 and 0x7FFFFF, rather than on a typical reading?

::: model
Most decoding bugs only show at the edges. A missing two's complement step gives a plausible number for small positive readings and only goes wrong once the top bit is set; an off-by-one in the scale factor is tiny in the middle and obvious at full scale. The extreme codes have answers you can work out exactly, −2.048 V and one count under +2.048 V, so they test the sign handling and the scaling where errors are largest and easiest to recognize.
:::
:::
