This is article 1 of 8 in a series about robust DS18B20 / 1-Wire system design.
Please see the introductory topic:
Logically Safe Usage / Fail Safe
I'm using this kind of sensors a lot and think that might be interesting for others.
This is not about topology, electromagnetic compatibility etc. but my way to deal logically safely with a special kind of “unusable” temperature values.
If you don't want to start i.e. a pump based on such values, especially the error code “-127”, or running the pump forever - here you go, cause the following typical if statement isn’t safe at all!
if (TempMeasured < TempDesired)
{
digitalWrite(RELAY_PIN, HIGH); // relay ON
}
else
{
digitalWrite(RELAY_PIN, LOW); // relay OFF
}
The trick is to normalize all those values by defintion to NAN (not a number), no matter what's the cause.
This helps you to make decisions in your code in a logically safe way, cause if one operand is NAN the result becomes NAN too.
That’s the above code, but logically safe:
if (sanitizeTemp(TempMeasured) < TempDesired)
{
digitalWrite(RELAY_PIN, HIGH); // relay ON
}
else // TempMeasured >= TempDesired or NAN
{
digitalWrite(RELAY_PIN, LOW); // relay OFF
}
IMPORTANT NOTE:
The suggested sanitizeTemp() function deals with special return values of the DallasTemperature library (which might not be familiar to everyone) and adds a very basic plausibility check while not altering a returned value. It is the lowest safety level which is imho absolutely necessary, but it can't help in any way with wrong values inside a plausible range!!!
Enough said, here is the very small sanitizeTemp() function - use at your own risk:
sanitizeTemp() function
// DS18B20 value normalization
// Explanation and background:
// https://forum.arduino.cc/t/ds18b20-engineering-resilience-practical-methods-for-robust-1-wire-systems/1433302
float sanitizeTemp(float t) // use this function to normalize errors by definition
{
// sensor error code (exactly -127.0)
if (t == -127.0) return NAN;
// sensor start value (exactly 85.0, almost never a real temperature)
if (t == 85.0) return NAN;
// physically no valid values
// DS18B20 nominally: -55 to +125 °C (use at least this as default!)
// depending on your application choose your limits for a plausibility check
if (t < 10.0 || t > 90.0) return NAN; // as an example!
// just a valid value
return t;
}
