[RESOLVED] DS18B20 Library Modifications

That return celsius; after the first read renders the following validity check null and void - why is this there? :confused:

The same applies to the return celsius; at the end of the while() loop.

You don’t want to return prematurely, but only when you’re done reading and possibly re-reading if you got an error.

try this

double getTemp(DS18B20 sensor) {
  int dsAttempts = 0;
  double celsius = NAN; // this requires #include <math.h> to define Not-A-Number to distinguish invalid values (0.0 is also valid) 
 
  if(!sensor.search()) {
    sensor.resetsearch();
    celsius = sensor.getTemperature();
    while (!sensor.crcCheck() && dsAttempts < 4) {
      Serial.printlnf("Caught bad value (%d)", ++dsAttempts);
      if (dsAttempts == 3) {
        delay(1000);
      }
      sensor.resetsearch();
      celsius = sensor.getTemperature();
    }
  }

  if (dsAttempts >= 4) return NAN;
  else return celsius;
}

After the function call you should check the return value for !isnan() before using it.