我正在尝试从DHT22读取温度和湿度,这是代码:
#include "fsm_config.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define DHTPIN D4 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
const int buttonPin = D5; // definicao do pino utilizado pelo botao
const int ledPin = D7; // definicao do pino utilizado pelo led
const char* ssid = "augusto-Aspire-E5-571"; // id da rede
const char* password = "sLPCwZqX"; // senha da rede
const char* mqtt_server = "things.ubidots.com"; // server
int buttonState = LOW; // armazena a leitura atual do botao
int lastButtonState = LOW; // armazena a leitura anterior do botao
unsigned long lastDebounceTime = 0; // armazena a ultima vez que a leitura da entrada variou
unsigned long debounceDelay = 50; // tempo utilizado para implementar o debounce
float umidade; //Stores humidity value
float temperatura; //Stores temperature value
String hum = "{\"value\":";
String temp = "{\"value\":";
char humChar[50];
char tempChar[50];
WiFiClient espClient;
PubSubClient client(espClient);
int lastMsg = 1000;
int now;
char msg[60];
char msg1[60];
int send_data() {
dht.begin();
umidade = dht.readHumidity();
temperatura = dht.readTemperature();
//Print temp and humidity values to serial monitor
Serial.print("Humidity: ");
Serial.print(umidade);
Serial.print(" %, Temp: ");
Serial.print(temperatura);
Serial.println(" Celsius");
temp.concat(temperatura);
temp.concat("}");
hum.concat(umidade);
hum.concat("}");
temp.toCharArray(tempChar, 50);
hum.toCharArray(humChar, 50);
String hum = "{\"value\":";
String temp = "{\"value\":";
client.publish("/v1.6/devices/wemos/umidade", humChar);
client.publish("/v1.6/devices/wemos/temp", humChar);
delay(10000); //Delay 2 sec.
return true;
}
但我只有&#34; NaN&#34;作为答案,应该怎么办?我在这里寻找其他一些问题,但没有一个对我有用。
这里是连接图像的链接:
答案 0 :(得分:0)
NaN代表&#34;不是数字&#34;。有时传感器无法读取并为您提供nan值。你不能对它做任何事情,但在DHT.h库中有一个名为isnan()的函数。因此,如果存储了最后一个正确的值,则可以创建备份变量。然后你可以检查你的传感器是否读为nan,如果是,你可以打印出备份变量:
float temperature;
float bTemperature;
temperature = dht.readTemperature();
if(!isnan(temperature)){
bTemperature = temperature;
Serial.println(temperature);
}
else{
Serial.println(bTemperature);
}