Some sensors I used (e.g. DHT11 for the temperature and humidity or CCS811 for measuring CO2 values) caused me really some nightmares. You know such time if your circuit alway stops for a strange reason and you are not able to find out what is the problem. One of the problem was the NaN value these sensors sometimes give. Unfortunatelly if you copy a basic code for these sensors from tutorials they usualy not care about this value and do not even mention it.
NaN value means "Not a Number". Yes, you hear well, you expect a number value from a sensor and it gives you sometimes a value that is not a number. If it is not a number it may cause malfunction of your code. Comparison functions will not work, the bluetooth module will be blocked, or the code stops if you use the NaN value in some functions like float(value)...
And the solution is very easy. Use isnan() function that checks if the value got from the sensor is the NaN value or not. Now I use it everywhere where I get a value from a sensor.
For example I had such function to check the temperature and humidity value from the DHT11 module that blocked the bluetooth communication:
void DisplayTempHum() {
float temp_f = dht.readTemperature();
float hum_f = dht.readHumidity();
byte temp = byte(temp_f);
byte hum = byte(hum_f);
SetTempHum(temp, hum); //sends values to the bluetooth module
}
A very small change made a diffrence. Now the code do not stop anything and work reliably for months:
void DisplayTempHum() {
float temp_f = dht.readTemperature();
float hum_f = dht.readHumidity();
if (isnan(temp_f) || isnan(hum_f)) return;
byte temp = byte(temp_f);
byte hum = byte(hum_f);
SetTempHum(temp, hum); //sends values to the bluetooth module
}
Comments
Please log in or sign up to comment.