16#ifndef NTC_THERMISTOR_CONVERSION_HPP
17#define NTC_THERMISTOR_CONVERSION_HPP
28namespace ntc_thermistor::detail {
32inline constexpr int64_t kInvScale = 4'294'967'296'000;
34inline constexpr int64_t kZeroCelsiusMk = 273'150;
36inline constexpr uint32_t kSearchSteps = 8U;
38inline constexpr uint64_t kPpm = 1'000'000U;
40inline constexpr uint64_t kMaxU32 = std::numeric_limits<uint32_t>::max();
43[[nodiscard]]
constexpr uint32_t FullScale(uint8_t bits)
noexcept {
44 return uint32_t{1U} << (bits & 31U);
48[[nodiscard]]
constexpr bool Ratiometric(
const Config& config)
noexcept {
49 return (config.adc_vref_mv == 0U) || (config.divider_supply_mv == 0U);
60[[nodiscard]]
constexpr Ratio NodeRatio(
const Config& config, uint32_t code)
noexcept {
61 const uint64_t scale = FullScale(config.adc_bits);
62 if (Ratiometric(config)) {
63 return Ratio{.num = code, .den = scale};
65 return Ratio{.num =
static_cast<uint64_t
>(code) * config.adc_vref_mv,
66 .den = scale * config.divider_supply_mv};
72[[nodiscard]]
constexpr uint32_t RailTop(
const Config& config)
noexcept {
73 const uint64_t scale = FullScale(config.adc_bits);
74 uint64_t rail = scale;
75 if (!Ratiometric(config) && (config.adc_vref_mv > config.divider_supply_mv)) {
76 rail = (scale * config.divider_supply_mv) / config.adc_vref_mv;
78 return static_cast<uint32_t
>((rail > 0U) ? (rail - 1U) : 0U);
87[[nodiscard]]
constexpr Error ClassifyCode(
const Config& config, uint32_t code)
noexcept {
88 const uint32_t scale = FullScale(config.adc_bits);
92 const uint32_t top = RailTop(config);
96 const uint32_t high_margin = low_side ? config.open_margin_codes : config.short_margin_codes;
97 const uint32_t low_margin = low_side ? config.short_margin_codes : config.open_margin_codes;
100 if ((high_margin >= top) || (code >= (top - high_margin))) {
106 return (code <= low_margin) ? low_fault :
Error::Ok;
111[[nodiscard]]
constexpr uint64_t FineQuotient(uint64_t numerator, uint64_t divisor)
noexcept {
116 const uint64_t whole = numerator / divisor;
117 const uint64_t part = DivRoundU((numerator % divisor) * kFineScale, divisor);
118 return SatAdd(SatMul(whole, kFineScale), part);
128[[nodiscard]]
constexpr uint64_t DividerFine(
const Config& config, uint32_t code)
noexcept {
129 const Ratio r = NodeRatio(config, code);
130 const uint64_t series = config.series_ohm;
132 return FineQuotient(SatMul(series, r.num), r.den - r.num);
134 return FineQuotient(SatMul(series, r.den - r.num), r.num);
138[[nodiscard]]
constexpr uint64_t RowFine(
const TablePoint& row)
noexcept {
139 return static_cast<uint64_t
>(row.resistance_ohm) * kFineScale;
144[[nodiscard]]
constexpr std::size_t FindSegment(std::span<const TablePoint> t,
145 uint64_t r)
noexcept {
147 std::size_t hi = t.size() - 1U;
148 for (uint32_t step = 0U; step < kSearchSteps; ++step) {
149 if ((hi - lo) <= 1U) {
152 const std::size_t mid = lo + ((hi - lo) / 2U);
153 if (RowFine(t[mid]) >= r) {
170[[nodiscard]]
constexpr int32_t Interpolate(
const TablePoint& a,
const TablePoint& b,
171 uint64_t r)
noexcept {
172 const int64_t la = Ln16(RowFine(a));
173 const int64_t lb = Ln16(RowFine(b));
174 const int64_t lr = Ln16(r);
176 return a.temperature_mc;
178 const int64_t span_t =
static_cast<int64_t
>(b.temperature_mc) - a.temperature_mc;
179 const int64_t t =
static_cast<int64_t
>(a.temperature_mc) + DivRound(span_t * (la - lr), la - lb);
180 return static_cast<int32_t
>(t);
185[[nodiscard]]
constexpr Result<int32_t> TableTemperature(std::span<const TablePoint> t,
186 uint64_t r)
noexcept {
187 const TablePoint& first = t[0];
188 const TablePoint& last = t[t.size() - 1U];
189 if (r > RowFine(first)) {
192 if (r < RowFine(last)) {
195 if (r == RowFine(last)) {
198 const std::size_t i = FindSegment(t, r);
204[[nodiscard]]
constexpr Result<int32_t> BetaTemperature(
const Curve& c, uint64_t r)
noexcept {
205 const int64_t x =
static_cast<int64_t
>(Ln16(r)) -
206 static_cast<int64_t
>(Ln16(
static_cast<uint64_t
>(c.r0_ohm) * kFineScale));
207 const int64_t term = DivRound(x * 65'536,
static_cast<int64_t
>(c.b_kelvin));
208 const int64_t t0_mk =
static_cast<int64_t
>(c.ref_temperature_mc) + kZeroCelsiusMk;
209 const int64_t sum = DivRound(kInvScale, t0_mk) + term;
213 const int64_t t_mc = DivRound(kInvScale, sum) - kZeroCelsiusMk;
214 if (t_mc > std::numeric_limits<int32_t>::max()) {
222inline constexpr uint64_t kShMaxFine = uint64_t{1U} << 40U;
225inline constexpr int64_t kShInvScale = 1'000'000'000'000'000'000;
227inline constexpr int64_t kQ16 = 65'536;
231[[nodiscard]]
constexpr Result<int32_t> ShTemperature(
const Curve& c, uint64_t r)
noexcept {
232 const uint64_t bounded = (r > kShMaxFine) ? kShMaxFine : r;
233 const int64_t x =
static_cast<int64_t
>(Ln16(bounded)) -
static_cast<int64_t
>(Ln16(kFineScale));
234 const int64_t x2 = DivRound(x * x, kQ16);
235 const int64_t x3 = DivRound(x2 * x, kQ16);
236 const int64_t inverse =
237 c.sh_a_e15 + DivRound(c.sh_b_e15 * x, kQ16) + DivRound(c.sh_c_e15 * x3, kQ16);
241 const int64_t t_mc = DivRound(kShInvScale, inverse) - kZeroCelsiusMk;
242 if (t_mc > std::numeric_limits<int32_t>::max()) {
249[[nodiscard]]
constexpr Result<int32_t> CurveTemperature(
const Curve& c, uint64_t r)
noexcept {
253 if (!c.table.empty()) {
254 return TableTemperature(c.table, r);
256 return (c.sh_b_e15 != 0) ? ShTemperature(c, r) : BetaTemperature(c, r);
260[[nodiscard]]
constexpr int32_t SaturatingAdd(int32_t a, int32_t b)
noexcept {
261 return ClampToInt32(
static_cast<int64_t
>(a) + b);
266[[nodiscard]]
constexpr int64_t ClampedTemperature(
const Curve& c, uint64_t r)
noexcept {
267 uint64_t clamped = r;
268 if (!c.table.empty()) {
269 const uint64_t hot = RowFine(c.table[c.table.size() - 1U]);
270 const uint64_t cold = RowFine(c.table[0]);
271 clamped = (r < hot) ? hot : r;
272 clamped = (clamped > cold) ? cold : clamped;
274 const Result<int32_t> t = CurveTemperature(c, clamped);
279 : std::numeric_limits<int32_t>::max();
284[[nodiscard]]
constexpr uint64_t ResistanceTerm(
const Curve& c, uint64_t r, int32_t t_mc,
285 uint32_t ppm)
noexcept {
289 const uint64_t delta = (SatMul(r, ppm) / kPpm) + 1U;
290 const uint64_t cold_r = SatAdd(r, delta);
291 const uint64_t hot_r = (delta >= r) ? uint64_t{1U} : (r - delta);
292 const uint64_t up = AbsDiff(ClampedTemperature(c, cold_r), t_mc);
293 const uint64_t down = AbsDiff(ClampedTemperature(c, hot_r), t_mc);
294 return (up > down) ? up : down;
303[[nodiscard]]
constexpr uint64_t BetaTerm(
const Curve& c, int32_t t_mc)
noexcept {
304 if (c.b_tol_ppm == 0U) {
307 const auto t_mk =
static_cast<uint64_t
>(
static_cast<int64_t
>(t_mc) + kZeroCelsiusMk);
309 static_cast<uint64_t
>(
static_cast<int64_t
>(c.ref_temperature_mc) + kZeroCelsiusMk);
310 const uint64_t per_unit = DivRoundU(
311 SatMul(t_mk, AbsDiff(
static_cast<int64_t
>(t_mk),
static_cast<int64_t
>(t0_mk))), t0_mk);
312 return DivRoundU(SatMul(per_unit, c.b_tol_ppm), kPpm);
317[[nodiscard]]
constexpr bool CodeUsable(
const Config& config, uint32_t code)
noexcept {
318 const bool inside = (code >= 1U) && (code < FullScale(config.adc_bits));
322 const Ratio r = NodeRatio(config, code);
323 return (r.num >= 1U) && (r.num < r.den);
328[[nodiscard]]
constexpr uint64_t NeighbourTerm(
const Config& config, uint32_t neighbour,
329 int32_t t_mc)
noexcept {
330 if (!CodeUsable(config, neighbour)) {
333 return AbsDiff(ClampedTemperature(config.curve, DividerFine(config, neighbour)), t_mc);
346[[nodiscard]]
constexpr uint32_t Uncertainty(
const Config& config, uint32_t code, uint64_t r,
347 int32_t t_mc)
noexcept {
348 const uint64_t up = NeighbourTerm(config, code + 1U, t_mc);
349 const uint64_t down = NeighbourTerm(config, code - 1U, t_mc);
350 uint64_t total = (up > down) ? up : down;
351 total = SatAdd(total, ResistanceTerm(config.curve, r, t_mc, config.curve.r_tol_ppm));
352 total = SatAdd(total, ResistanceTerm(config.curve, r, t_mc, config.series_tol_ppm));
353 total = SatAdd(total, BetaTerm(config.curve, t_mc));
354 total = SatAdd(total, config.curve.curve_error_mc);
355 total = (total < 1U) ? uint64_t{1U} : total;
356 return static_cast<uint32_t
>((total > kMaxU32) ? kMaxU32 : total);
360[[nodiscard]]
constexpr Result<uint64_t> FineOfCode(
const Config& config, uint32_t code)
noexcept {
361 const Error fault = ClassifyCode(config, code);
369[[nodiscard]]
constexpr uint64_t WholeOhms(uint64_t fine)
noexcept {
370 return DivRoundU(fine, kFineScale);
375[[nodiscard]]
constexpr Result<uint32_t> ResistanceOfCode(
const Config& config,
376 uint32_t code)
noexcept {
377 const Result<uint64_t> fine = FineOfCode(config, code);
381 const uint64_t ohms = WholeOhms(fine.value);
382 if (ohms > kMaxU32) {
389[[nodiscard]]
constexpr Result<Reading> ConvertCode(
const Config& config, uint32_t code)
noexcept {
390 const Result<uint64_t> fine = FineOfCode(config, code);
394 const uint64_t ohms = WholeOhms(fine.value);
395 if (ohms > kMaxU32) {
398 const Result<int32_t> t = CurveTemperature(config.curve, fine.value);
402 if (t.value < config.min_temperature_mc) {
405 if (t.value > config.max_temperature_mc) {
409 Reading{.temperature_mc = SaturatingAdd(t.value, config.offset_mc),
410 .resistance_ohm =
static_cast<uint32_t
>(ohms),
412 .uncertainty_mc = Uncertainty(config, code, fine.value, t.value)});
435 return detail::ConvertCode(config, mean_code);
447 uint32_t mean_code)
noexcept {
451 return detail::ResistanceOfCode(config, mean_code);
460 return detail::SaturatingAdd(mc,
static_cast<int32_t
>(detail::kZeroCelsiusMk));
469 const int64_t scaled = detail::DivRound(
static_cast<int64_t
>(mc) * 9, int64_t{5});
470 return detail::ClampToInt32(scaled + 32'000);
486 uint32_t r_ntc_ohm)
noexcept {
487 if (config.divider_supply_mv == 0U) {
490 const uint64_t supply = config.divider_supply_mv;
491 const uint64_t total =
static_cast<uint64_t
>(config.series_ohm) + r_ntc_ohm;
492 const uint64_t volts_squared_r = (supply * supply) * r_ntc_ohm;
493 const uint64_t p = detail::DivRoundU(detail::DivRoundU(volts_squared_r, total), total);
494 return static_cast<uint32_t
>((p > detail::kMaxU32) ? detail::kMaxU32 : p);
Error
Why a call failed. Values 0 to 9 are the shared base set; this driver's own values start at 16.
Definition ntc_thermistor_types.hpp:45
constexpr Error Validate(const Config &config) noexcept
Check a configuration without touching the hardware.
Definition ntc_thermistor_types.hpp:435
@ InvalidArgument
A Config is out of range or inconsistent; nothing was read.
The NTC thermistor driver: everything it declares lives here; internals in detail.
Definition ntc_thermistor.hpp:25
constexpr int32_t ToMilliFahrenheit(int32_t mc) noexcept
A temperature in milli-degrees Fahrenheit.
Definition ntc_thermistor_conversion.hpp:468
constexpr uint32_t SelfHeatingMicrowatts(const Config &config, uint32_t r_ntc_ohm) noexcept
The power the divider puts into the thermistor, in microwatts: V^2 * Rn / (Rs + Rn)^2.
Definition ntc_thermistor_conversion.hpp:485
constexpr Result< uint32_t > ConvertResistance(const Config &config, uint32_t mean_code) noexcept
The thermistor's resistance for a code: the divider arithmetic only, with no curve and no window.
Definition ntc_thermistor_conversion.hpp:446
constexpr Result< Reading > Convert(const Config &config, uint32_t mean_code) noexcept
The pure conversion: the maths for an ADC code, with no port and no state.
Definition ntc_thermistor_conversion.hpp:431
constexpr int32_t ToMilliKelvin(int32_t mc) noexcept
A temperature in milli-kelvin.
Definition ntc_thermistor_conversion.hpp:459
Compile-time helpers of the NTC_THERMISTOR driver: typed integer literals, exact hook matching and en...
Integer arithmetic of the NTC thermistor driver: a binary logarithm, rounded division and saturating ...
Public types of the NTC thermistor driver: errors, Result<T>, the curve and the configuration,...
Everything one thermistor and its divider need. There is no default part: a Config{} fails Validate()...
Definition ntc_thermistor_types.hpp:284
The value of a call, or why there is none.
Definition ntc_thermistor_types.hpp:120
static constexpr Result Failure(Error e) noexcept
A failed result.
Definition ntc_thermistor_types.hpp:145
static constexpr Result Success(T v) noexcept
A successful result.
Definition ntc_thermistor_types.hpp:137