---
title: "Embedded lab: signals in and out"
heading: Sine tables, DDS, thermistor tables, quantization and filters, in Python and C
eyebrow: C12 · Lesson 26 · Embedded lab
xp: 50
---

::: hook
The analog half of the course (the ADC, fixed point, filtering, PWM and the DAC) comes down to tables and integer arithmetic worked out in advance. Firmware stores a sine table instead of calling `sin`, a thermistor table instead of computing a logarithm, and a filter as a shift instead of a multiply. This lab generates those tables in Python, measures how accurate they are, checks the quantization limit of the converters, and then runs the integer smoother from the filtering lesson in C on the board.
:::

::: play
- The curve is the error of a thermistor table with linear interpolation: the table holds the exact temperature every `step` ADC codes, and readings in between are interpolated.
- The error is zero at the table's points and largest between them, and worst at the ends of the range, where the thermistor's curve bends most.
- Halve the step: the error drops by about a factor of four, as linear interpolation's error should. A 17-entry table (step 256) is within about 0.74 °C from code 512 to 3584; 33 entries bring it to 0.23 °C.
:::

```sim plot
view: graph
x: c = 512..3584 codes
y: e = -0.4..1 °C
slider: s = 64..512 step 64 = 256
samples: 1500
plot: 1/(1/298.15 + ln((4095 - floor(c/s)*s)/(floor(c/s)*s))/3950) + (c - floor(c/s)*s)/s*(1/(1/298.15 + ln((4095 - floor(c/s)*s - s)/(floor(c/s)*s + s))/3950) - 1/(1/298.15 + ln((4095 - floor(c/s)*s)/(floor(c/s)*s))/3950)) - 1/(1/298.15 + ln((4095 - c)/c)/3950) | label: table error
```

::: predict
## A 12-bit converter is driven by a full-scale sine. What signal-to-quantization-noise ratio does a perfect one give?

- [ ] 12 dB
- [ ] 48 dB
- [x] About 74 dB
- [ ] 120 dB

::: reveal
$6.02N + 1.76 = 74.0$ dB for N = 12. Each extra bit is worth 6 dB. The lab measures it directly by quantizing a sine and comparing the error's power with the signal's.
:::
:::

::: nameit
## The tables

- **Sine table:** $n$ entries, $\lfloor 2047.5 + 2047.5\sin(2\pi k/n) + 0.5\rfloor$, spanning the DAC's 0 to 4095.
- **DDS step:** $\text{step} = \text{round}(f \cdot 2^{32}/f_s)$, giving exactly $\text{step} \cdot f_s/2^{32}$.
- **Thermistor table:** the exact temperature every `step` codes; in between, linear interpolation, whose error grows with the square of the step.
- **Quantization:** a full-scale sine on an ideal N-bit converter has an SNR of $6.02N + 1.76$ dB.

The thermistor here is the course's: 10 kΩ at 25 °C, B = 3950 K, from 3.3 V to the pin, with 10 kΩ to ground, so $R = 10\text{ kΩ} \times (4095 - c)/c$ for code c.
:::

::: check
kind: python

## Write `sine_table(n)`: n entries of $\lfloor 2047.5 + 2047.5\sin(2\pi k/n) + 0.5\rfloor$ for k = 0 to n − 1, and `dds(f, fs, bits=32)`: return (step, actual frequency) for a phase accumulator of that many bits.

```python starter
import math

def sine_table(n):
    return [0] * n

def dds(f, fs, bits=32):
    return (0, 0.0)
```

```python solution
import math

def sine_table(n):
    return [math.floor(2047.5 + 2047.5 * math.sin(2 * math.pi * k / n) + 0.5) for k in range(n)]

def dds(f, fs, bits=32):
    step = round(f * 2 ** bits / fs)
    return (step, step * fs / 2 ** bits)
```

```python tests
t = sine_table(32)
assert t[0] == 2048 and t[8] == 4095 and t[24] == 0, "Mid-scale, top and bottom at k = 0, 8 and 24."
assert t[1] == 2447, "k = 1: 2047.5 + 2047.5 sin(π/16) rounds to 2447."
step, f = dds(440, 10000)
assert step == 188978561 and abs(f - 440) < 1e-6, "440 Hz at 10 kHz: within a microhertz."
assert dds(1000, 8000) == (536870912, 1000.0), "1 kHz at 8 kHz is exactly 2^32/8."
```

::: right
Right. A 32-bit accumulator tunes to microhertz; the table's length sets the waveform's quality, not its frequency.
:::
:::

::: check
kind: python

## Write `adc_to_temp(code)`: the exact temperature in °C for the course's thermistor at ADC code `code`. Then `max_table_error(lo, hi, step)`: build a table of exact temperatures at multiples of `step` and return the largest absolute error of linear interpolation for codes `lo` to `hi` inclusive.

```python starter
import math

def adc_to_temp(code):
    return 25.0

def max_table_error(lo, hi, step):
    return 0.0
```

```python solution
import math

def adc_to_temp(code):
    r = 10000 * (4095 - code) / code
    return 1 / (1 / 298.15 + math.log(r / 10000) / 3950) - 273.15

def max_table_error(lo, hi, step):
    def interp(c):
        i = c // step
        a, b = adc_to_temp(i * step), adc_to_temp((i + 1) * step)
        return a + (c - i * step) / step * (b - a)
    return max(abs(interp(c) - adc_to_temp(c)) for c in range(lo, hi + 1))
```

```python tests
assert abs(adc_to_temp(2482) - 35.02) < 0.01, "Code 2482 is 35.0 °C, as in the sensor lesson."
e256 = max_table_error(512, 3584, 256)
e128 = max_table_error(512, 3584, 128)
assert abs(e256 - 0.738) < 0.002, "Step 256: about 0.74 °C at worst."
assert abs(e128 - 0.228) < 0.002, "Step 128: about 0.23 °C."
assert 3 < e256 / e128 < 4.2, "Halving the step cuts the error by roughly four."
```

::: right
Right. The table costs 17 or 33 entries; the logarithm it replaces would cost thousands of cycles in software floating point.
:::
:::

::: check
kind: python

## Write `sqnr(bits, n=4096)`: quantize $\sin(2\pi \cdot 7k/n)$, k = 0 to n − 1, to `bits` bits over −1 to 1 (map to 0 to $2^\text{bits} - 1$, round to the nearest code, map back), and return the ratio of the signal's power to the error's power in dB.

```python starter
import math

def sqnr(bits, n=4096):
    return 6.02 * bits
```

```python solution
import math

def sqnr(bits, n=4096):
    q = 2 ** bits - 1
    s = [math.sin(2 * math.pi * 7 * k / n) for k in range(n)]
    x = [round((v + 1) / 2 * q) / q * 2 - 1 for v in s]
    ps = sum(v * v for v in s) / n
    pe = sum((a - b) ** 2 for a, b in zip(s, x)) / n
    return 10 * math.log10(ps / pe)
```

```python tests
assert abs(sqnr(8) - 49.92) < 0.5, "8 bits: about 49.9 dB."
assert abs(sqnr(12) - 74.0) < 0.5, "12 bits: about 74 dB."
assert 5.5 < (sqnr(12) - sqnr(8)) / 4 < 6.5, "About 6 dB per bit."
```

::: right
Right. The measured values land within a tenth of a decibel of $6.02N + 1.76$.
:::
:::

::: check
kind: python

## Write `smooth(xs, k)`: the integer exponential smoother with state `s` starting at `xs[0] << k`, updated by `s += x - (s >> k)` for every sample, outputting `s >> k`. Then `settle(xs, k, target, tol)`: the index of the first output within `tol` of `target` that stays within it for the rest of the list, or `None`.

```python starter
def smooth(xs, k):
    return list(xs)

def settle(xs, k, target, tol):
    return None
```

```python solution
def smooth(xs, k):
    s, out = xs[0] << k, []
    for x in xs:
        s += x - (s >> k)
        out.append(s >> k)
    return out

def settle(xs, k, target, tol):
    y = smooth(xs, k)
    for i in range(len(y)):
        if all(abs(v - target) <= tol for v in y[i:]):
            return i
    return None
```

```python tests
data = [100] * 4 + [900] * 8 + [400] * 4
assert smooth(data, 2) == [100, 100, 100, 100, 300, 450, 562, 647, 710, 757, 793, 820, 715, 636, 577, 533], "The smoother on a step up and a step down."
assert settle([0] + [1000] * 200, 4, 1000, 10) == 71, "k = 4 needs about 71 samples to come within 1%."
assert settle([0] * 5, 2, 1000, 10) is None, "Never gets there."
```

::: right
Right. The settling index matches $\ln 0.01/\ln(15/16) = 71.4$ from the filtering lesson.
:::
:::

::: check
kind: c
run: 0.01
expect: print = 647, 820, 533

## Run the smoother with k = 2 over these sixteen readings on the board: state starting at the first reading shifted left by 2, `s += x - (s >> 2)`, output `s >> 2`. Print the outputs after the 8th, 12th and 16th readings.

```c starter
#include "board.h"

const int data[16] = {100, 100, 100, 100, 900, 900, 900, 900,
                      900, 900, 900, 900, 400, 400, 400, 400};

int main(void) {
    print(data[7]);
    print(data[11]);
    print(data[15]);
    return 0;
}
```

```c solution
#include "board.h"

const int data[16] = {100, 100, 100, 100, 900, 900, 900, 900,
                      900, 900, 900, 900, 400, 400, 400, 400};

int main(void) {
    int s = data[0] << 2;
    for (int i = 0; i < 16; i++) {
        s += data[i] - (s >> 2);
        if (i == 7 || i == 11 || i == 15)
            print(s >> 2);
    }
    return 0;
}
```

::: right
Right. The board's results match the Python model exactly, which is the point of having one.
:::
:::

::: explain
## Why does linear interpolation in a thermistor table get four times more accurate when the table's step is halved?

::: model
Between two table points, interpolation replaces the curve with a straight chord. The gap between a smooth curve and its chord is set by how much the curve bends over that interval: it's about one-eighth of the second derivative times the square of the interval's width. Halving the step halves the width, so the gap shrinks by a factor of four. That's why the error is worst where the thermistor's curve bends most, at the ends of the range, and why a modest increase in table size buys a large gain in accuracy.
:::
:::
