MAX31855: How to skip invalid values
Using the MAX31855 as a thermocouple amplifier & digitizer sometimes leads to invalid values, be it due to noise on the analog (thermocouple) side or due to digital signal integrity issues such as GND noise.
This code modified from our post on ESP32 MAX31855 thermocouple LCD minimal example using PlatformIO provides an example of how to skip & ignore those values, but report an error if more than 10 (configurable) consecutive values are invalid.
Depending on your application, you might need to choose a more suitable temperature range in IsValidReading()
. Choosing a valid range as narrow as possible will avoid more bad values being sent to downstream code.
SPIClass vspi(VSPI);
Adafruit_MAX31855 thermocouple1(Pin_MAX31855_A_CS, &vspi);
bool IsValidReading(double reading) {
return !isnan(reading) && reading > -40.0 && reading < 1000.0;
}
void ReadTemperature() {
double celsius = thermocouple1.readCelsius();
if(!IsValidReading(celsius)) {
consecutiveNaNReads++;
if(consecutiveNaNReads >= maxConsecutiveNaNReads) {
// Thermocouple is disconnected
Serial.println("Thermocouple error");
}
} else {
consecutiveNaNReads = 0;
Serial.println(celsius);
}
}