Skip to content

API guide

The API by task, with code that compiles (the host build compiles every example on this page).

Datasheet sections this page relies on

From Public references n/a n/a:

  • Self-heating power: Dissipated power, P = V_s^2 R_n / (R_s + R_n)^2, p. 1

All of them, with the driver API for each: Datasheet map.

The object

NtcThermistor<Port> holds a reference to your port and a Config. The constructor does no I/O and cannot fail. The object is not copyable or movable.

Call Returns What it does
EnsureInitialized() Result<void> Checks the configuration, brings the port's ADC up and switches the divider off. Returns Ok with no I/O once it has succeeded
IsInitialized() bool Whether EnsureInitialized() has succeeded
Read() Result<Reading> Samples, converts, returns the temperature, resistance, mean code and bound
ReadResistance() Result<uint32_t> The same sampling, stopping at the divider arithmetic: ohms
ReadRawCode() Result<uint32_t> One raw conversion in the same bias sequence, with no averaging and no maths: a diagnostic, no retry
GetLastCode() uint32_t The last code the port returned, even one out of scale; no I/O
SetConfig(config) Result<void> Replaces the configuration after validating it; the old one stays on failure
GetConfig() const Config& The configuration in use

Free functions, in inc/ntc_thermistor_conversion.hpp, with no port and no state:

Function What it does
Convert(config, code) The conversion of a code: the same maths as Read()
ConvertResistance(config, code) The divider arithmetic only
ToMilliKelvin(mc), ToMilliFahrenheit(mc) Unit conversions, saturating
SelfHeatingMicrowatts(config, r_ohm) The power the divider puts into the part
Validate(config) The configuration check

Read a temperature

quickstart.cpp
#include "ntc_thermistor.hpp"
#include "ntc_thermistor_presets.hpp"

// A 10 kOhm / B 3950 thermistor low-side in a 10 kOhm divider on a 12-bit ADC,
// valid from -40 to +125 degC.
constexpr ntc_thermistor::Config kConfig{.curve = ntc_thermistor::presets::kGeneric10kB3950,
                                         .min_temperature_mc = -40'000,
                                         .max_temperature_mc = 125'000};

int read_temperature_mc(MyPort& port, int32_t& milli_celsius) {
  ntc_thermistor::NtcThermistor<MyPort> sensor(port, kConfig); // no I/O yet

  if (auto r = sensor.EnsureInitialized(); !r) { // 1. check the config, bring the ADC up
    return static_cast<int>(r.error);            //    InvalidArgument or Bus
  }
  const auto t = sensor.Read(); // 2. sample, divider to ohms, curve to temperature
  if (!t) {
    return static_cast<int>(t.error); //    OpenCircuit, ShortCircuit, BelowRange, ...
  }
  milli_celsius = t.value.temperature_mc; // 3. milli-degrees Celsius;
                                          // t.value.uncertainty_mc bounds it
  return 0;
}

Reading has temperature_mc (milli-degrees Celsius, window and offset applied), resistance_ohm, code (the mean) and uncertainty_mc (a bound on the declared tolerances).

Use the maths alone

api_tasks.cpp
// The maths alone: a code the application already has, no port, no state.
int32_t TemperatureOfCode(uint32_t code) {
  const auto r = ntc_thermistor::Convert(kConfig, code);
  return r ? r.value.temperature_mc : INT32_MIN;
}

Convert validates the configuration first, so the same call checks a Config and a code in a unit test of your own application.

Handle every error

api_tasks.cpp
const char* Explain(ntc_thermistor::Error e) {
  switch (e) {
  case ntc_thermistor::Error::OpenCircuit:
    return "no thermistor: cut wire, missing part, or a divider that is not "
           "powered";
  case ntc_thermistor::Error::ShortCircuit:
    return "node at the other rail: shorted part or wire, or the divider "
           "supply collapsed";
  case ntc_thermistor::Error::BelowRange:
    return "colder than the curve or the window";
  case ntc_thermistor::Error::AboveRange:
    return "hotter than the curve or the window";
  case ntc_thermistor::Error::Unstable:
    return "the samples disagree: a floating or noisy input";
  case ntc_thermistor::Error::CodeOutOfScale:
    return "the port returns more bits than Config::adc_bits says";
  default:
    break;
  }
  return ntc_thermistor::ToString(e);
}
Error Value When
NotInitialized 1 A read before EnsureInitialized() succeeded
InvalidArgument 2 The configuration is out of range or inconsistent (including a wait the port cannot make)
Bus 3 ReadRaw() or SetBias() returned false
OpenCircuit 16 The node is at the open rail: cut wire, missing part, divider not powered
ShortCircuit 17 The node is at the short rail: shorted part or wire
BelowRange 18 Colder than the curve or the window, or a resistance that does not fit 32 bits
AboveRange 19 Hotter than the curve or the window, or a resistance of zero
Unstable 20 The samples differ by more than max_spread_codes
CodeOutOfScale 21 A sample is at or above 2^adc_bits

Timeout, DeviceIdMismatch, Crc, Busy, DeviceFault and Unsupported are never returned: a thermistor has no bus, no identity and no checksum.

Trust a reading only as far as its bound

api_tasks.cpp
// The reading is a value and a bound: the true temperature lies within it if
// the declared tolerances hold.
bool WithinOneKelvin(ntc_thermistor::NtcThermistor<MyPort>& sensor, int32_t& temperature_mc) {
  const auto t = sensor.Read();
  if (!t || (t.value.uncertainty_mc > 1000U)) {
    return false;
  }
  temperature_mc = t.value.temperature_mc;
  return true;
}

Change the configuration at run time

api_tasks.cpp
// Change the offset at run time (a calibration): validated first, the old one
// stays on failure.
bool Calibrate(ntc_thermistor::NtcThermistor<MyPort>& sensor, int32_t offset_mc) {
  ntc_thermistor::Config c = sensor.GetConfig();
  c.offset_mc = offset_mc;
  return sensor.SetConfig(c).ok();
}

Other units

reference.cpp
// Milli-kelvin and milli-fahrenheit, saturating; no floating point anywhere.
int32_t ToFahrenheit(int32_t milli_celsius) {
  return ntc_thermistor::ToMilliFahrenheit(milli_celsius);
}

Next: Configuration.