Embedded HandbookApps
All sections › IX. The C language: from basics to advanced
STM32F103, STM32F407, STM32G031 · level intermediate · 8 min read
Open in the interactive handbook

76п. A table with linear interpolation instead of a formula: a uniform grid, binary search, how many nodes are needed and what logf costs

A thermistor, a thermocouple, a nonlinear pressure sensor, a battery charge curve — all have a formula with a logarithm, a power or a polynomial. On a chip without a floating-point unit such a formula drags in kilobytes of software arithmetic, and on a fast chip — extra microseconds in an interrupt. The usual replacement is a table of values at nodes and a straight line between neighbouring nodes. Section 96.3 applied it to a thermistor; here is the technique itself: how to lay out a table so as not to search for the segment, when a search is needed after all, and how many nodes give the required accuracy — with the error measured on all 4096 ADC codes.

Grounds: alg.c (three methods: a uniform table, binary search, a formula with logf) was built with gcc 12.2.0 on a computer (stm-sys:1) and run by host.c — the error of each method against the exact formula in double precision on all codes; the tables were printed by gen.py. The same alg.c was built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) for Cortex-M4F and Cortex-M0; extra.sh builds two whole programs — with the formula and with the table — and compares their size.

Terms used in the documentation

Term Meaning
piecewise linear interpolation a straight line between neighbouring table nodes
node, knot a table node: a point where the value is given exactly
uniform grid, power-of-two step a uniform grid with a power-of-two step
non-uniform grid nodes denser where the curve bends
interval search finding the segment the argument falls into
interpolation error ∝ h² the error of a line grows as the square of the step
newlib-nano libm a small C library with maths for microcontrollers
table generator a program that prints a table for the source code

In plain words. Instead of computing the formula every time, compute it once on a computer at a few dozen points and put the numbers into Flash. On the device find the two neighbouring points and draw a straight line between them. The denser the points — the closer the line to the curve, and twice as dense is four times as accurate.


76п.1 An example: a thermistor and its formula

A 10 kΩ NTC thermistor with B = 3950 to ground, a 10 kΩ pull-up to the ADC supply, 12 bits. The code gives the resistance, the resistance gives the temperature through a logarithm:

    float r = 10000.0f * c / (4096.0f - c);
    float t = 1.0f / (1.0f / 298.15f + logf(r / 10000.0f) / 3950.0f) - 273.15f;

The "code → temperature" curve is strongly nonlinear: around 25 °C one code is 0.022 °C, around 100 °C already 0.125 °C. The table must take this into account.

76п.2 The computer prints the table

Numbers are not typed into the table by hand: a generator prints them — here gen.py in Python — by the same formula, and the check compares the table in the source with the generator's output. Changed the thermistor or the pull-up — rerun the generator. The temperature is stored as integer hundredths of a degree in int16_t: −40.00…125.00 °C fit, and all the interpolation is integer.

76п.3 A uniform grid: a node without a search

If the nodes stand 128 codes apart, the segment number is the top 5 bits of the code and the position inside it the bottom 7:

int16_t ntc_uniform(uint16_t code)
{
    uint32_t k = code >> 7, f = code & 127u;
    int32_t a = ntc_u[k], b = ntc_u[k + 1];
    return (int16_t)(a + ((b - a) * (int32_t)f) / 128);
}

33 nodes of 2 bytes — 66 bytes, not a single loop or comparison, the division by 128 is a shift. This is the fastest variant, it fits right into an ADC interrupt. Its weakness: the nodes stand equally dense both where the curve is almost straight and where it bends sharply.

76п.4 A non-uniform grid: binary search for the segment

The nodes can be placed by temperature — every 15, 10 or 5 °C. Then their codes go unevenly, and the segment has to be found:

    uint32_t lo = 0, hi = n - 1; /* code_tab[lo] <= code < code_tab[hi] */
    while (hi - lo > 1) {
        uint32_t mid = (lo + hi) / 2;
        if (code_tab[mid] <= code)
            lo = mid;
        else
            hi = mid;
    }

A binary search over 34 nodes is 5–6 steps against up to 33 when scanning from the start, as in 96.3. The price is 4 bytes per node (code and temperature) and a division by the segment length: on Cortex-M0 that is a call to __aeabi_idiv.

The thermistor curve, the table nodes and the error of the line between them

76п.5 Experiment: three methods on all ADC codes

Each method was run on all 4096 codes, the error is against the formula in double precision:

Method table bytes error in −20…100 °C error in −40…125 °C
uniform, 33 nodes 66 0.86 °C 2.76 °C
binary search, 12 nodes 48 1.11 °C 1.46 °C
formula with logf 0 0.01 °C 0.01 °C

A uniform grid is good in the middle and bad at the edges: at −40 °C and above 100 °C the curve bends most, and the nodes there are no denser than in the middle — 2.76 °C over the whole range. Nodes by temperature are spread more evenly along the curve: 12 nodes give 1.46 °C over the whole range. The formula with logf is off by 0.01 °C — that is rounding to hundredths.

76п.6 How many nodes are needed: the error as the square of the step

The same binary search with ever denser nodes:

Node step nodes table bytes error in −20…100 °C
15.0 °C 12 48 1.11 °C
10.0 °C 17 68 0.52 °C
5.0 °C 34 136 0.13 °C
2.5 °C 67 268 0.06 °C

Half the step — a quarter of the error (0.52 → 0.13 for a step of 10 → 5 °C): a line departs from a smooth curve by an amount proportional to the square of the segment length and the curvature. The last row stands out (0.13 → 0.06, not 0.03) because the error already runs into the rounding of the nodes to whole codes. Hence the rule: divide the required accuracy by the error at some step, take the square root — and you get how many times denser the nodes must be.

At equal memory a non-uniform grid is more accurate: 17 nodes by temperature (68 bytes) — 0.52 °C against 0.86 °C for 33 uniform nodes (66 bytes). But the uniform one needs no search and no division.

76п.7 What logf costs

Function sizes on Cortex-M4F and Cortex-M0:

Function Cortex-M4F, bytes Cortex-M0, bytes
ntc_uniform 44 44
lut_search 108 100
ntc_formula 180 168

The formula function itself is no larger than the search — but it calls logf and lrintf, and on Cortex-M0 seven more software floating-point routines (__aeabi_fmul, __aeabi_fdiv and their neighbours). The real price shows in a whole program with newlib-nano:

Program Cortex-M0, code bytes Cortex-M4F, code bytes
with the formula 6132 2008
with the table 1232 1132

On Cortex-M0 the formula adds 4900 bytes — a quarter of Flash on a 16 KB chip. On Cortex-M4F with a floating-point unit — 876 bytes: hardware multiplication and division, but logf stays a library routine.

76п.8 The table edges and a broken sensor

A code beyond the table is not "very cold" or "very hot" but a broken wire (a code at the top edge) or a short circuit (near zero). lut_search returns the edge value of the table — on a screen that is a lie. In a device the edge codes are checked separately and a sensor error is shown, as in 96.3.

76п.9 When a table and when a formula

76п.10 Pitfalls

Nodes typed by hand. A typo in one node gives a step on a 15 °C segment that nobody notices. A generator prints the table, a check compares it (76п.2).

An index past the last node. In a uniform table k + 1 at the maximum code is 32: the array must have 33 nodes, not 32.

Overflow in the interpolation. (b − a) · f with hundredths of a degree and 7 bits of fraction is almost 300 thousand: it does not fit in int16_t, compute in int32_t.

A uniform grid over the whole range. 0.86 °C in the middle and 2.76 °C at the edges (76п.5): either cut the edges or take a non-uniform grid.

An edge value instead of a sensor error. A broken wire is shown as 125 °C (76п.8).


76п.11 Summary

Check yourself

  1. How many times will the interpolation error decrease if the nodes are placed twice as densely? - A) Twice - B) About four times: the error is proportional to the square of the step - C) It will not change - D) Eight times
  2. What is good about a uniform grid with a step of 128 codes? - A) It is more accurate than a non-uniform one at the same memory - B) It does not need to be generated - C) The segment number is the top bits of the code: no search, no division - D) It needs no edge checks
  3. Why is the formula with logf expensive on Cortex-M0? - A) logf compiles slowly - B) It drags in software floating point and the library logarithm — +4900 bytes of program - C) Cortex-M0 cannot call functions - D) It is inaccurate

Check yourself: answers - 1 — B. Why: Experiment: step 10 → 5 °C, error 0.52 → 0.13 °C (76п.6). - 2 — C. Why: code >> 7 is the node number, code & 127 the fraction, division by 128 a shift (76п.3). - 3 — B. Why: The whole program: 6132 bytes with the formula against 1232 with the table (76п.7).

Next: section 77 "Compilation and compilers".

Open in the interactive handbook