NTC_THERMISTOR Driver 0.1.0
API reference
Loading...
Searching...
No Matches
ntc_thermistor_conversion.hpp
Go to the documentation of this file.
1
16#ifndef NTC_THERMISTOR_CONVERSION_HPP
17#define NTC_THERMISTOR_CONVERSION_HPP
18
19#include <cstddef>
20#include <cstdint>
21#include <limits>
22#include <span>
23
27
28namespace ntc_thermistor::detail {
29
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();
41
43[[nodiscard]] constexpr uint32_t FullScale(uint8_t bits) noexcept {
44 return uint32_t{1U} << (bits & 31U);
45}
46
48[[nodiscard]] constexpr bool Ratiometric(const Config& config) noexcept {
49 return (config.adc_vref_mv == 0U) || (config.divider_supply_mv == 0U);
50}
51
53struct Ratio {
54 uint64_t num{0};
55 uint64_t den{1};
56};
57
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};
64 }
65 return Ratio{.num = static_cast<uint64_t>(code) * config.adc_vref_mv,
66 .den = scale * config.divider_supply_mv};
67}
68
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;
77 }
78 return static_cast<uint32_t>((rail > 0U) ? (rail - 1U) : 0U);
79}
80
87[[nodiscard]] constexpr Error ClassifyCode(const Config& config, uint32_t code) noexcept {
88 const uint32_t scale = FullScale(config.adc_bits);
89 if (code >= scale) {
91 }
92 const uint32_t top = RailTop(config);
93 const bool low_side = config.topology == Topology::NtcLowSide;
94 // The margins belong to the faults, not to the rails: the rails swap with the
95 // topology.
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;
98 const Error high_fault = low_side ? Error::OpenCircuit : Error::ShortCircuit;
99 const Error low_fault = low_side ? Error::ShortCircuit : Error::OpenCircuit;
100 if ((high_margin >= top) || (code >= (top - high_margin))) {
101 return high_fault;
102 }
103 // Below the high margin the node ratio is below 1 (the top is the supply's,
104 // not the ADC's, when the reference is above the supply), and above the low
105 // margin it is above 0.
106 return (code <= low_margin) ? low_fault : Error::Ok;
107}
108
111[[nodiscard]] constexpr uint64_t FineQuotient(uint64_t numerator, uint64_t divisor) noexcept {
112 if (divisor == 0U) {
113 return kMaxU64; // not reachable from a classified code; keeps the division
114 // defined
115 }
116 const uint64_t whole = numerator / divisor;
117 const uint64_t part = DivRoundU((numerator % divisor) * kFineScale, divisor);
118 return SatAdd(SatMul(whole, kFineScale), part);
119}
120
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;
131 if (config.topology == Topology::NtcLowSide) {
132 return FineQuotient(SatMul(series, r.num), r.den - r.num);
133 }
134 return FineQuotient(SatMul(series, r.den - r.num), r.num);
135}
136
138[[nodiscard]] constexpr uint64_t RowFine(const TablePoint& row) noexcept {
139 return static_cast<uint64_t>(row.resistance_ohm) * kFineScale;
140}
141
144[[nodiscard]] constexpr std::size_t FindSegment(std::span<const TablePoint> t,
145 uint64_t r) noexcept {
146 std::size_t lo = 0U;
147 std::size_t hi = t.size() - 1U;
148 for (uint32_t step = 0U; step < kSearchSteps; ++step) {
149 if ((hi - lo) <= 1U) {
150 break;
151 }
152 const std::size_t mid = lo + ((hi - lo) / 2U);
153 if (RowFine(t[mid]) >= r) {
154 lo = mid;
155 } else {
156 hi = mid;
157 }
158 }
159 return lo;
160}
161
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);
175 if (la <= lb) {
176 return a.temperature_mc;
177 }
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);
181}
182
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)) {
191 }
192 if (r < RowFine(last)) {
194 }
195 if (r == RowFine(last)) {
196 return Result<int32_t>::Success(last.temperature_mc);
197 }
198 const std::size_t i = FindSegment(t, r);
199 return Result<int32_t>::Success(Interpolate(t[i], t[i + 1U], r));
200}
201
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;
210 if (sum <= 0) {
212 }
213 const int64_t t_mc = DivRound(kInvScale, sum) - kZeroCelsiusMk;
214 if (t_mc > std::numeric_limits<int32_t>::max()) {
216 }
217 return Result<int32_t>::Success(static_cast<int32_t>(t_mc));
218}
219
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;
228
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);
238 if (inverse <= 0) {
240 }
241 const int64_t t_mc = DivRound(kShInvScale, inverse) - kZeroCelsiusMk;
242 if (t_mc > std::numeric_limits<int32_t>::max()) {
244 }
245 return Result<int32_t>::Success(static_cast<int32_t>(t_mc));
246}
247
249[[nodiscard]] constexpr Result<int32_t> CurveTemperature(const Curve& c, uint64_t r) noexcept {
250 if (r == 0U) {
252 }
253 if (!c.table.empty()) {
254 return TableTemperature(c.table, r);
255 }
256 return (c.sh_b_e15 != 0) ? ShTemperature(c, r) : BetaTemperature(c, r);
257}
258
260[[nodiscard]] constexpr int32_t SaturatingAdd(int32_t a, int32_t b) noexcept {
261 return ClampToInt32(static_cast<int64_t>(a) + b);
262}
263
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;
273 }
274 const Result<int32_t> t = CurveTemperature(c, clamped);
275 if (t) {
276 return t.value;
277 }
278 return (t.error == Error::BelowRange) ? std::numeric_limits<int32_t>::min()
279 : std::numeric_limits<int32_t>::max();
280}
281
284[[nodiscard]] constexpr uint64_t ResistanceTerm(const Curve& c, uint64_t r, int32_t t_mc,
285 uint32_t ppm) noexcept {
286 if (ppm == 0U) {
287 return 0U;
288 }
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;
295}
296
303[[nodiscard]] constexpr uint64_t BetaTerm(const Curve& c, int32_t t_mc) noexcept {
304 if (c.b_tol_ppm == 0U) {
305 return 0U;
306 }
307 const auto t_mk = static_cast<uint64_t>(static_cast<int64_t>(t_mc) + kZeroCelsiusMk);
308 const auto t0_mk =
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);
313}
314
317[[nodiscard]] constexpr bool CodeUsable(const Config& config, uint32_t code) noexcept {
318 const bool inside = (code >= 1U) && (code < FullScale(config.adc_bits));
319 if (!inside) {
320 return false;
321 }
322 const Ratio r = NodeRatio(config, code);
323 return (r.num >= 1U) && (r.num < r.den);
324}
325
328[[nodiscard]] constexpr uint64_t NeighbourTerm(const Config& config, uint32_t neighbour,
329 int32_t t_mc) noexcept {
330 if (!CodeUsable(config, neighbour)) {
331 return 0U;
332 }
333 return AbsDiff(ClampedTemperature(config.curve, DividerFine(config, neighbour)), t_mc);
334}
335
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);
357}
358
360[[nodiscard]] constexpr Result<uint64_t> FineOfCode(const Config& config, uint32_t code) noexcept {
361 const Error fault = ClassifyCode(config, code);
362 if (fault != Error::Ok) {
363 return Result<uint64_t>::Failure(fault);
364 }
365 return Result<uint64_t>::Success(DividerFine(config, code));
366}
367
369[[nodiscard]] constexpr uint64_t WholeOhms(uint64_t fine) noexcept {
370 return DivRoundU(fine, kFineScale);
371}
372
375[[nodiscard]] constexpr Result<uint32_t> ResistanceOfCode(const Config& config,
376 uint32_t code) noexcept {
377 const Result<uint64_t> fine = FineOfCode(config, code);
378 if (!fine) {
379 return Result<uint32_t>::Failure(fine.error);
380 }
381 const uint64_t ohms = WholeOhms(fine.value);
382 if (ohms > kMaxU32) {
384 }
385 return Result<uint32_t>::Success(static_cast<uint32_t>(ohms));
386}
387
389[[nodiscard]] constexpr Result<Reading> ConvertCode(const Config& config, uint32_t code) noexcept {
390 const Result<uint64_t> fine = FineOfCode(config, code);
391 if (!fine) {
392 return Result<Reading>::Failure(fine.error);
393 }
394 const uint64_t ohms = WholeOhms(fine.value);
395 if (ohms > kMaxU32) {
397 }
398 const Result<int32_t> t = CurveTemperature(config.curve, fine.value);
399 if (!t) {
400 return Result<Reading>::Failure(t.error);
401 }
402 if (t.value < config.min_temperature_mc) {
404 }
405 if (t.value > config.max_temperature_mc) {
407 }
409 Reading{.temperature_mc = SaturatingAdd(t.value, config.offset_mc),
410 .resistance_ohm = static_cast<uint32_t>(ohms),
411 .code = code,
412 .uncertainty_mc = Uncertainty(config, code, fine.value, t.value)});
413}
414
415} // namespace ntc_thermistor::detail
416
417namespace ntc_thermistor {
418
431[[nodiscard]] constexpr Result<Reading> Convert(const Config& config, uint32_t mean_code) noexcept {
432 if (Validate(config) != Error::Ok) {
434 }
435 return detail::ConvertCode(config, mean_code);
436}
437
446[[nodiscard]] constexpr Result<uint32_t> ConvertResistance(const Config& config,
447 uint32_t mean_code) noexcept {
448 if (Validate(config) != Error::Ok) {
450 }
451 return detail::ResistanceOfCode(config, mean_code);
452}
453
459[[nodiscard]] constexpr int32_t ToMilliKelvin(int32_t mc) noexcept {
460 return detail::SaturatingAdd(mc, static_cast<int32_t>(detail::kZeroCelsiusMk));
461}
462
468[[nodiscard]] constexpr int32_t ToMilliFahrenheit(int32_t mc) noexcept {
469 const int64_t scaled = detail::DivRound(static_cast<int64_t>(mc) * 9, int64_t{5});
470 return detail::ClampToInt32(scaled + 32'000);
471}
472
485[[nodiscard]] constexpr uint32_t SelfHeatingMicrowatts(const Config& config,
486 uint32_t r_ntc_ohm) noexcept {
487 if (config.divider_supply_mv == 0U) {
488 return 0U;
489 }
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);
495}
496
497} // namespace ntc_thermistor
498
499#endif // NTC_THERMISTOR_CONVERSION_HPP
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.
@ Ok
The call succeeded.
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