Calibration Table Interpolation
A thermistor is calibrated with a table of (ADC reading, temperature in 0.1 °C) points, sorted by ADC value. Write int16_t adc_to_temp(uint16_t adc) that:
- finds the two table entries surrounding
adcwith a binary search, - linearly interpolates between them using integer arithmetic only,
- clamps to the first or last temperature when
adcis outside the table.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Binary-search for the first entry whose adc is ≥ the input. Then interpolate with t0 + (t1 - t0) * (x - x0) / (x1 - x0) using 32-bit signed math.
#include <stdio.h>
#include <stdint.h>
typedef struct { uint16_t adc; int16_t temp; } cal_t;
static const cal_t table[] = {
{ 500, 850 }, { 1000, 600 }, { 1800, 350 }, { 2600, 150 }, { 3400, -100 },
};
#define TABLE_LEN (sizeof table / sizeof table[0])
int16_t adc_to_temp(uint16_t adc)
{
if (adc <= table[0].adc) return table[0].temp;
if (adc >= table[TABLE_LEN - 1].adc) return table[TABLE_LEN - 1].temp;
size_t lo = 1, hi = TABLE_LEN - 1; /* first index with table[i].adc >= adc */
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
if (table[mid].adc < adc) lo = mid + 1;
else hi = mid;
}
const cal_t *a = &table[lo - 1], *b = &table[lo];
int32_t dt = (int32_t)b->temp - a->temp;
int32_t dx = (int32_t)b->adc - a->adc;
return (int16_t)(a->temp + dt * (int32_t)(adc - a->adc) / dx);
}
A piecewise-linear table in flash is how most firmware linearises non-linear sensors (thermistors, flow sensors, battery discharge curves), because it is far cheaper than evaluating the Steinhart-Hart equation with floating point. Binary search keeps lookup O(log n), which matters for large tables; for evenly spaced ADC points you can compute the index directly.
Watch for overflow in dt * (adc - a->adc) when tables have large ranges, and note that integer division truncates towards zero. Add dx / 2 with the right sign for rounding if needed.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(adc_to_temp(100) == 850); /* below table */
CHECK(adc_to_temp(500) == 850);
CHECK(adc_to_temp(750) == 725); /* halfway 850..600 */
CHECK(adc_to_temp(1800) == 350);
CHECK(adc_to_temp(2200) == 250);
CHECK(adc_to_temp(3000) == 25); /* 150 + (-250 * 400 / 800) */
CHECK(adc_to_temp(4095) == -100); /* above table */
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}