calibration: Multi-point calibration library

A sensor rarely reports the quantity it measures. A thermistor returns a resistance, an ADC channel returns a code, a bridge returns a voltage, and the relation between that number and the physical value is non-linear, differs from sensor to sensor and drifts with the batch. Datasheets usually give a formula, but the formula describes a typical part, not the one on the board.

The component solves that with a table of calibration points: you write down a few pairs “raw code -> true value”, measured once with a reference instrument, and the library computes the value for any code in between. The table is small (a handful of points for a thermistor, a couple of dozens for an RTD and a few hundred for a pressure sensor) and it is cheap in both code size and run time: a lookup and a couple of multiplications, no floating-point series, no logarithms unless the method asks for them.

Points are stored sorted by the raw code, so they may be added in any order, a repeated code replaces the earlier point, and a whole batch may be added at once. Nothing is computed in calibration_add_point(): calibration_prepare() validates the table and precomputes what the chosen method needs, which keeps the search and the evaluation branch-free and lets the library report a bad table once, instead of failing on every reading.

Interpolation methods

The shape of the curve between the points matters, and different sensors need different shapes. The method is chosen when the handle is initialized and can not be changed afterwards.

CALIBRATION_LINEAR

A polyline: the value is interpolated linearly between the two surrounding points. The result is continuous, never leaves the interval between the neighbouring values and never needs more than two points, but its derivative jumps at every point. This is the right choice for a sensor which is nearly linear over the range of interest, and for a dense table where the segments are short enough for the kinks to be invisible.

CALIBRATION_LOG_LINEAR

A straight line in the (ln(code), value) plane: the raw code is logarithmic, the calibrated value is linear. An NTC thermistor, a photo resistor or any other sensor whose resistance depends exponentially on the measured quantity need exactly that: a linear table over such a sensor is useless over a wide range, a logarithmic one is accurate with five points. The raw codes must be positive.

CALIBRATION_LOG_LOG

A straight line in the (ln(code), ln(value)) plane, for a sensor with a power-law response, value = a * code^b: a flow meter, a hot-wire anemometer, a strain gauge bridge with a non-linear excitation. Both the raw codes and the calibrated values must be positive.

CALIBRATION_PCHIP

Monotone cubic Hermite interpolation (the Fritsch-Carlson variant): a smooth curve with a continuous derivative, which passes exactly through the points and, unlike an ordinary cubic spline, never overshoots the interval between two neighbouring values. No overshoot matters when the value is physically bounded or when the sensor is known to be monotone: a spline may report a negative pressure or a temperature above the boiling point between two perfectly sane points. It needs at least three points and is the best default for a smooth sensor with a sparse table: an RTD, a thermocouple, a load cell.

CALIBRATION_PCHIP_LOG

The same monotone cubic curve over the logarithm of the raw code, for an exponential sensor whose table is too sparse even for the log-linear method.

No method fits every sensor, and the difference is not academic: on a thermistor table of five points the linear method may be off by several degrees in the middle of the range, the log-linear one by a fraction of a degree, and the monotone cubic one by less than the sensor itself.

Two-dimensional table

A quantity may depend on two arguments: the output of a pressure sensor depends on the temperature of the die as well, the reading of a gas sensor depends on the humidity, the voltage of a battery depends on the load. A list of points can not describe such a surface, so the component has a separate type, calibration_grid_t, with a rectangular table of rows by cols cells and bilinear interpolation inside a cell. The table must be filled completely, and the number of distinct values along each axis must match the declared size, otherwise calibration_grid_prepare() refuses it: a hole in the table would otherwise be interpolated across silently.

Values outside the range

Both the one-dimensional and the two-dimensional tables extrapolate: outside the range the outermost segment (or the outermost row and column of cells) is continued. It is a deliberate choice - a sensor in an unplanned mode still has to return something plausible, and refusing the value would break the application exactly when the reading matters most - but it is not silent: calibration_prepare() warns once that the table does not cover the range, and every value taken from outside the range is logged at the debug level.

Example

An NTC thermistor calibrated with five points; the raw codes are ADC readings, the values are degrees Celsius measured with a reference thermometer.

#include <esp_err.h>
#include <esp_log.h>
#include <calibration.h>

static calibration_handle_t thermistor;

void app_main(void)
{
    ESP_ERROR_CHECK(calibration_init(&thermistor, 5, CALIBRATION_LOG_LINEAR));

    ESP_ERROR_CHECK(calibration_add_point(&thermistor, 8060.0f, -20.0f));
    ESP_ERROR_CHECK(calibration_add_point(&thermistor, 3720.0f, 0.0f));
    ESP_ERROR_CHECK(calibration_add_point(&thermistor, 1810.0f, 25.0f));
    ESP_ERROR_CHECK(calibration_add_point(&thermistor, 925.0f, 50.0f));
    ESP_ERROR_CHECK(calibration_add_point(&thermistor, 505.0f, 75.0f));

    ESP_ERROR_CHECK(calibration_prepare(&thermistor));

    float temperature;
    esp_err_t res = calibration_get_value(&thermistor, 1810.0f, &temperature);
    if (res == ESP_OK)
        ESP_LOGI("app", "Temperature: %.2f C", temperature);
    else
        ESP_LOGE("app", "Could not calibrate the reading: %s", esp_err_to_name(res));
}

The same handle is safe to query from any task once it is prepared, and it is released with calibration_free(). See examples/default for the one-dimensional methods and examples/grid for the two-dimensional table.

Enums

enum calibration_method_t

Approximation methods.

The methods interpolate the calibrated value between the calibration points. Values outside the range of the points are always extrapolated with the outermost segment, see calibration_prepare().

Values:

enumerator CALIBRATION_LINEAR

Piecewise linear interpolation of the value against the raw value.

Usually enough for a dense calibration table.

enumerator CALIBRATION_LOG_LINEAR

Piecewise linear interpolation of the value against the natural logarithm of the raw value.

Use it when the dependence is exponential, e.g. for thermistors or photo resistors. Requires positive raw values.

enumerator CALIBRATION_LOG_LOG

Piecewise linear interpolation against the natural logarithms of both the raw value and the calibrated value, e.g.

for flow meters and other sensors with a power-law transfer function. Requires positive raw values and positive calibrated values.

enumerator CALIBRATION_PCHIP

Monotone cubic Hermite interpolation (Fritsch-Carlson).

Smoother than the piecewise linear one and never overshoots the neighbouring points, unlike an ordinary cubic spline. Requires at least three points.

enumerator CALIBRATION_PCHIP_LOG

Monotone cubic Hermite interpolation against the natural logarithm of the raw value.

Requires at least three points and positive raw values.

Functions

esp_err_t calibration_init(calibration_handle_t *handler, size_t count, calibration_method_t type)

Init calibration handle.

Allocates memory to store calibration points and fills the handle. The handle must be zeroed before the first call, e.g. calibration_handle_t handler = { 0 };.

Parameters:
  • handler – Pointer to calibration handle structure

  • count – Maximum number of calibration points, at least 2

  • type – Approximation method

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if handler is NULL or count is less than 2

  • ESP_ERR_NOT_SUPPORTED if type is unknown

  • ESP_ERR_INVALID_STATE if the handle is already initialized

  • ESP_ERR_NO_MEM if the point list could not be allocated

esp_err_t calibration_add_point(calibration_handle_t *handler, float code, float value)

Add calibration point.

The point is inserted into the list, which is kept ordered by the raw value. If a point with the same raw value already exists, its calibrated value is replaced. Both values must be finite: NaN and infinities are rejected, because they break the ordering of the list.

The log methods require positive raw values, and CALIBRATION_LOG_LOG additionally requires positive calibrated values, so such a point is rejected before it reaches the list.

Adding a point invalidates the result of calibration_prepare().

Parameters:
  • handler – Pointer to calibration handle structure

  • code – Raw value

  • value – Calibrated value

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if handler is NULL, the handle is not initialized, one of the values is not finite, or the point does not suit the selected method (non-positive raw value for the log methods, non-positive calibrated value for CALIBRATION_LOG_LOG)

  • ESP_ERR_INVALID_STATE if the point list is full

esp_err_t calibration_add_points(calibration_handle_t *handler, const calibration_point_t *points, size_t count)

Add multiple calibration points.

Either all points are added or none of them: the free space and the values are checked before the first point is stored.

Adding points invalidates the result of calibration_prepare().

Parameters:
  • handler – Pointer to calibration handle structure

  • points – Array of calibration points

  • count – Number of calibration points to add

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if handler or points is NULL, the handle is not initialized, or one of the points is not finite or does not suit the selected method

  • ESP_ERR_INVALID_STATE if the points do not fit into the list

esp_err_t calibration_prepare(calibration_handle_t *handler)

Prepare the handle for the calculations.

Checks that the list contains enough points for the selected method (two for the linear methods, three for the monotone interpolation) and computes the derivatives used by CALIBRATION_PCHIP and CALIBRATION_PCHIP_LOG. For the linear methods the call only validates the list, so the application does not have to branch on the method.

The call also warns once that values outside the range of the points are extrapolated.

Parameters:

handler – Pointer to calibration handle structure

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if handler is NULL or the handle is not initialized

  • ESP_ERR_INVALID_STATE if the list does not contain enough points

  • ESP_ERR_NO_MEM if the derivatives could not be allocated

esp_err_t calibration_get_value(const calibration_handle_t *handler, float code, float *value)

Get calibrated value by raw value.

The value is interpolated with the method selected in calibration_init(). A raw value equal to one of the points returns that point’s calibrated value. Raw values outside the range of the points are extrapolated using the outermost segment, so the result is a continuation of the curve, not a clamp. Every such call is logged at the debug level.

calibration_prepare() must be called after the points are added.

Parameters:
  • handler – Pointer to calibration handle structure

  • code – Raw value, must be finite and positive for the log methods

  • value – [out] Calculated calibrated value

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if handler or value is NULL, the handle is not initialized, code is not finite or is not positive while a log method is selected

  • ESP_ERR_INVALID_STATE if calibration_prepare() was not called after the last change of the point list

esp_err_t calibration_free(calibration_handle_t *handler)

Free calibration handle.

Releases the point list and the internal buffers. The handle can be initialized again after that.

Note

The library is not thread-safe and does not lock the handle.

Note

Fields of calibration_handle_t are filled by the library and must not be modified by the application.

Parameters:

handler – Pointer to calibration handle structure

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if handler is NULL

esp_err_t calibration_grid_init(calibration_grid_t *grid, size_t rows, size_t cols)

Init calibration grid.

Allocates memory to store rows times cols points and fills the handle. The handle must be zeroed before the first call, e.g. calibration_grid_t grid = { 0 };.

Parameters:
  • grid – Pointer to calibration grid structure

  • rows – Number of distinct values of the second argument, at least 2

  • cols – Number of distinct values of the first argument, at least 2

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if grid is NULL, rows or cols is less than 2, or their product overflows

  • ESP_ERR_INVALID_STATE if the grid is already initialized

  • ESP_ERR_NO_MEM if the point list could not be allocated

esp_err_t calibration_grid_add_point(calibration_grid_t *grid, float x, float y, float value)

Add grid point.

If a point with the same pair of arguments already exists, its calibrated value is replaced. All three values must be finite.

Adding a point invalidates the result of calibration_grid_prepare().

Parameters:
  • grid – Pointer to calibration grid structure

  • x – Raw value of the first argument

  • y – Raw value of the second argument

  • value – Calibrated value

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if grid is NULL, the grid is not initialized, or one of the values is not finite

  • ESP_ERR_INVALID_STATE if the grid is full

esp_err_t calibration_grid_add_points(calibration_grid_t *grid, const calibration_grid_point_t *points, size_t count)

Add multiple grid points.

Either all points are added or none of them.

Parameters:
  • grid – Pointer to calibration grid structure

  • points – Array of grid points

  • count – Number of grid points to add

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if grid or points is NULL, the grid is not initialized, or one of the points is not finite

  • ESP_ERR_INVALID_STATE if the points do not fit into the grid

esp_err_t calibration_grid_prepare(calibration_grid_t *grid)

Prepare the grid for the calculations.

Checks that every cell of the grid is filled and that the points contain exactly rows distinct values of the second argument and cols distinct values of the first one, then builds the sorted axes and the dense matrix.

The call also warns once that values outside the grid are extrapolated.

Parameters:

grid – Pointer to calibration grid structure

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if grid is NULL or the grid is not initialized

  • ESP_ERR_INVALID_STATE if the grid is incomplete or the number of distinct values does not match the declared size

  • ESP_ERR_NO_MEM if the internal buffers could not be allocated

esp_err_t calibration_grid_get_value(const calibration_grid_t *grid, float x, float y, float *value)

Get calibrated value by the pair of raw values.

The value is bilinearly interpolated between the four surrounding grid points. Values outside the grid are extrapolated using the outermost cells, so the result is a continuation of the surface, not a clamp. Every such call is logged at the debug level.

calibration_grid_prepare() must be called after the points are added.

Parameters:
  • grid – Pointer to calibration grid structure

  • x – Raw value of the first argument, must be finite

  • y – Raw value of the second argument, must be finite

  • value – [out] Calculated calibrated value

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if grid or value is NULL, the grid is not initialized, or x or y is not finite

  • ESP_ERR_INVALID_STATE if calibration_grid_prepare() was not called after the last change of the point list

esp_err_t calibration_grid_free(calibration_grid_t *grid)

Free calibration grid.

Releases the point list and the internal buffers. The grid can be initialized again after that.

Note

The library is not thread-safe and does not lock the grid.

Note

Fields of calibration_grid_t are filled by the library and must not be modified by the application.

Parameters:

grid – Pointer to calibration grid structure

Returns:

  • ESP_OK on success

  • ESP_ERR_INVALID_ARG if grid is NULL

struct calibration_point_t
#include <calibration.h>

Calibration point.

Public Members

float code

Raw value.

float value

Calibrated value.

struct calibration_handle_t
#include <calibration.h>

Calibration handler.

The fields marked as internal are filled by the library.

Public Members

calibration_method_t type

Approximation method, filled by calibration_init()

calibration_point_t *points

Ordered list of calibration points, filled by the library.

size_t count

Maximum number of calibration points, filled by calibration_init()

size_t filled

Current number of calibration points, filled by the library.

float *slopes

Internal: derivatives of the monotone interpolation.

bool prepared

Internal: set by calibration_prepare()

struct calibration_grid_point_t
#include <calibration.h>

Grid point.

Public Members

float x

Raw value of the first argument.

float y

Raw value of the second argument.

float value

Calibrated value.

struct calibration_grid_t
#include <calibration.h>

Calibration grid.

A two-dimensional calibration table for quantities which depend on two arguments, e.g. a pressure sensor compensated by temperature.

The fields marked as internal are filled by the library.

Public Members

calibration_grid_point_t *points

Unordered list of grid points, filled by the library.

size_t rows

Number of distinct Y values, filled by calibration_grid_init()

size_t cols

Number of distinct X values, filled by calibration_grid_init()

size_t capacity

Maximum number of grid points, filled by calibration_grid_init()

size_t filled

Current number of grid points, filled by the library.

float *xs

Internal: sorted distinct X values.

float *ys

Internal: sorted distinct Y values.

float *values

Internal: dense matrix, rows by cols.

bool prepared

Internal: set by calibration_grid_prepare()