Photon Maker Kit - DS18B20 - temperature sensing issues/questions

I have a few suggestions to clean up your code. You have your two libraries included twice, so you should remove one set of those. There’s no reason to create the Spark.variable, “tempCheck” since the variable it monitors is the same one you’re looking at with “tempf”. The syntax you’re using for the Spark variables is the old syntax; there’s no need for the ampersand or the type any more (should also switch to Particle from Spark, although they both work). The variable tempCheck doesn’t need to be global since you only use it within the loop function as a temporary place to hold the temperature value until you do the validity check. The validity check can be done with a single “if” statement, no need for an “else”; the statement tempC = tempC doesn’t do anything, so is not needed.

#include "OneWire/OneWire.h"
#include "spark-dallas-temperature/spark-dallas-temperature.h"

double tempC = 0.0;
double tempF = 0.0;
int tempSensorPin = D2;

OneWire oneWire(tempSensorPin);
DallasTemperature sensors(&oneWire);

void setup() {
    sensors.begin();
    Particle.variable("tempc", tempC);
    Particle.variable("tempf", tempF);
}

void loop() {
  sensors.requestTemperatures();
  double tempCheck = sensors.getTempCByIndex(0);
  
  if ( tempCheck > -50 && tempCheck < 50) // might want to guard against a spurious high value as well
  {
    tempC = tempCheck;
    tempF = tempC * 9.0 / 5.0 + 32.0;
  }
  delay(1000);
}

Other ways to throw out bad values would be more robust. One way, if your timing allows you to do it, is to take multiple readings close together, put those values into an array, sort that array, then take the center value, or an average of several of the center values. This way, any spurious low or high values end up at the beginning or end of the array, and get thrown out. I gave an example of this here

1 Like