ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
mics_math.h
Go to the documentation of this file.
1#pragma once
2// Pure math of the MiCS-5524 vendor model; the per-gas constants live in coefficients.py.
3// x = VCC - V_ao, ratio = x / x_air (sampled in clean air), ppm = (threshold - ratio) / gain.
4// No ESPHome dependencies, so the host tests cover it.
5
6#include <cmath>
7
9
12 float threshold;
13 float gain;
14 float min_ppm;
15 float max_ppm;
16};
17
20inline float air_value_from_voltage(float voltage, float vcc) {
21 if (!std::isfinite(voltage) || !std::isfinite(vcc) || voltage <= 0.0f || voltage > vcc)
22 return NAN;
23 return vcc - voltage;
24}
25
27inline constexpr float MAX_CALIBRATION_SPREAD = 0.25f;
28
30inline bool calibration_is_stable(float min_value, float max_value, float mean) {
31 if (!std::isfinite(min_value) || !std::isfinite(max_value) || !std::isfinite(mean) || mean <= 0.0f)
32 return false;
33 return max_value - min_value <= MAX_CALIBRATION_SPREAD * mean;
34}
35
37inline float ratio_from_air_value(float x, float x_air) {
38 if (!std::isfinite(x) || x < 0.0f || !std::isfinite(x_air) || x_air <= 0.0f)
39 return NAN;
40 return x / x_air;
41}
42
45inline float ppm_from_vendor_curve(float ratio, const VendorCurve &curve) {
46 if (!std::isfinite(ratio))
47 return NAN;
48 if (ratio > curve.threshold)
49 return 0.0f;
50
51 const float ppm = (curve.threshold - ratio) / curve.gain;
52 if (ppm < curve.min_ppm)
53 return 0.0f;
54 if (ppm > curve.max_ppm)
55 return curve.max_ppm;
56 return ppm;
57}
58
59} // namespace esphome::mics_5524::micsmath
bool calibration_is_stable(float min_value, float max_value, float mean)
True when the clean-air samples spread at most MAX_CALIBRATION_SPREAD of their mean.
Definition mics_math.h:30
constexpr float MAX_CALIBRATION_SPREAD
Largest relative spread (max - min) / mean a clean-air calibration accepts.
Definition mics_math.h:27
float air_value_from_voltage(float voltage, float vcc)
x = VCC - V_ao: 0 at VCC (a saturated sensor, never clean air).
Definition mics_math.h:20
float ratio_from_air_value(float x, float x_air)
ratio = x / x_air (NaN when either value is unusable).
Definition mics_math.h:37
float ppm_from_vendor_curve(float ratio, const VendorCurve &curve)
ratio -> ppm as DFRobot_MICS getGasData(): 0 above the threshold or below the vendor range,...
Definition mics_math.h:45
Per-gas constants of the vendor model.
Definition mics_math.h:11
float max_ppm
upper end of the measuring range
Definition mics_math.h:15
float threshold
ratio at or below which the gas counts as detected
Definition mics_math.h:12
float min_ppm
the vendor reports 0 ppm below this
Definition mics_math.h:14
uint16_t x
Definition tt21100.cpp:5