Heart beat for DHT22 MQTT

I have a Wemos D1 mini with DHT22 sending data via MQTT to my Raspberry Pi3 dashboard. It's just a simple two gauge dashboard reporting temperature and humidity. My problem is the DHT22 occasionally goes into "NaN" mode and my dashboard simply reports the last good data it received.
has anyone created a heartbeat indicator on my dashboard that would confirm good data?

In my personal experience the DHT are not the best choice, I had tested time ago and finally moved in most of the cases to BME280 that is what I recommend you.

With DHT one of the main issues is the power supply, try to provide a proper 5VDC direct supply but in my case even that was giving random NaN readings( what means is not sending data) and have tested several ways without being able to run totally out of it.

Regarding heartbeat you can use the trigger node to monitor if signal gets lost after x time.

Regards

I think I'll take your advice and go with the BME280. For $8.99 and free shipping it's a no brainer.
Thanks for the input.

1 Like

Try AliExpress Charles, they are MUCH cheaper there

yes 3-4€ max unless you are in a hurry and purchase locally

Are you using an Arduino sketch? If so aren't you checking the reading before sending the value? here is the check in the sketch I use:

 // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

Here is the complete sketch:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
#include "config.h"

#include "DHT.h"
#define DHTPIN D4        // what pin we're connected to
#define DHTTYPE DHT22    // DHT 22  (AM2302)
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
//String msg = msg1;
char msg_to_send[500];
int len = 0;

// ================================
void setup() {
// ================================
  setup_serial();
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  setup_wifi();                     // go connect to the wifi network
  client.setServer(mqtt_server, mqtt_port);
}

// ================================
// =   start of LOOP              =
// ================================
void loop() {
// --------------------------------
  if (!client.connected()) {
    mqtt_reconnect();
  }
  client.loop();
// --------------------------------

  // Wait a few seconds between measurements.
  delay(2000);  // 2 seconds

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
 
 // form a JSON-formatted string:
//  String msg = "{\"type\":\"";
//  msg += type;
//  msg += "\",\"id\":\"";
//  msg += id;
//  msg += "\",\"room\":\"";
//  msg += room;
//  msg += "\",\"temperature\":\"";
//  msg += String(t);
//  msg += "\",\"humidity\":\"";
//  msg += String(h);
//  msg +="\"}";

// MQTT_TOPIC: location/room/device/sensorid/value

  // form a JSON-formatted string:
  String msg1 = "{\"room\":\"";
  String msg2 = room;
  String msg3 = "\",\"device\":\"";
  String msg4 = device;
  String msg5 = "\",\"id\":\"";
  String msg6 = id;
  String msg7 = "\",\"temp\":\"";
  String msg8 = String(t);
  String msg9 = "\",\"humi\":\"";
  String msg10 = String(h);
  String msg11 ="\"}";
  String msg = msg1 + msg2 + msg3 + msg4 + msg5 + msg6 + msg7 + msg8 + msg9 + msg10 + msg11;
  // print it:
  
  long now = millis();
  if (now - lastMsg > 10000) {
    lastMsg = now;
    msg.trim();
    len = msg.length();
    msg.toCharArray(msg_to_send, len+1);
 
    if (debug) Serial.println(msg_to_send);

    client.publish(mqtt_topic, msg_to_send);
  }
   #ifdef FORCE_DEEPSLEEP
     if (debug) Serial.println("Force deepsleep 15min!");
     ESP.deepSleep(15 * 60 * 1000000);
     delay(100);
   #endif
   delay(1000*60*15);  //wait 15 minutes to send next reading

}
// ================================
// =   end of LOOP                =
// ================================

// --------------------------------
void setup_serial() {
// --------------------------------
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}
// --------------------------------

// --------------------------------
void mqtt_reconnect() {
// --------------------------------
  // Loop until we're reconnected
  while (!client.connected()) {
    if (debug) Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266test-";
    clientId += String(random(0xffff), HEX);
 
    // Attempt to connect
    if (client.connect(clientId.c_str(),mqtt_lwt,0,1,mqtt_lwt_msg)) {
      
      if (debug) Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish(mqtt_connect, mqtt_connect_msg);
      // ... and resubscribe
      // client.subscribe("inTopic");
      
    } else {
      if (debug) Serial.print("failed, rc=");
      if (debug) Serial.print(client.state());
      if (debug) Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
// --------------------------------

// --------------------------------
void setup_wifi() {
// --------------------------------
  if (debug) {
    Serial.print("Attempting to connect to WPA SSID ");
    Serial.println(ssid);
    Serial.println(ssid_pswd);
  }

  WiFi.begin(ssid, ssid_pswd);   //this doesn't???

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if (debug) Serial.print(".");
  }
  

  // you're connected now, so print out the data:
  if (debug) Serial.println("You're connected to the network");
  if (debug) printWifiData();
}

// --------------------------------
void printWifiData() {
// --------------------------------
  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP address: ");
  Serial.println(ip);

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  Serial.print(mac[5], HEX);
  Serial.print(":");
  Serial.print(mac[4], HEX);
  Serial.print(":");
  Serial.print(mac[3], HEX);
  Serial.print(":");
  Serial.print(mac[2], HEX);
  Serial.print(":");
  Serial.print(mac[1], HEX);
  Serial.print(":");
  Serial.println(mac[0], HEX);

}

And here is the config.h for the sketch:

// MQTT_TOPIC: location/room/device/sensorid/value

// WiFi configuration
const char* ssid            = "Your SSID";
const char* ssid_pswd       = "password";

//MQTT configuration
const char* mqtt_server      = "192.168.nnn.nnn";
const int   mqtt_port        =  1883;

// Device configuration - location/room/device
const char* address          = "mainst";
const char* room             = "Office";
const char* device            = "dht22";
const char* id               = "office1";
//
const char* mqtt_topic       = "mainst/office/wemos";
const char* mqtt_connect     = "mainst/office/wemos/connect";
const char* mqtt_lwt         = "mainst/office/wemos/will";
const bool  mqtt_auth        = true;
const char* mqtt_user        = "user";
const char* mqtt_pass        = "pass";
const char* mqtt_lwt_msg     = "The mainst office DHT22 is OFF line";
const char* mqtt_connect_msg = "The mainst office DHT22 is now ON line";
//
const bool  debug           = true;

Hope it helps.

The lalest dashboard gauge (if you are using gauges) should show "NaN" if indeed that is what you are sending them... (actually any text so up to you to make sure it is "NaN" if that is your choice :slight_smile:

image

I normally would but waiting 12 to 22 days is to long to wait this time. And it's been, more often than not lately, the 22 days.
UGH! Just got notice that my 2day amazon prime delivery is delayed. Maybe I could have gotten it from China sooner.

I'm sending data from Wemos D1 mini via MQTT to node-red on my Pi3 so arduino magic won't work. :anguished:

I'm on node-red-dashboard v2.9.6 is that the latest?
I'm not familiar with how to update from the palette manager.

yeah that's the latest

Actually it's not transmitting anything. I checked my DHT22 and the light wasn't blinking so I reseated the unit and the blink returned but i'm getting a "NaN" in the devices list in ESPEasy and nothing is reaching the Pi.
I think it might be bad dupont connectors...

That sketch is running on a Wemos D1 mini via MQTT to Node-RED on a Pi and has been for a year and a half....

Oh you're using ESPeasy - ok, that is a different story.

1 Like

This is an old thread, I am sure that you resolved this issue. I came across the same problem and I wrapped it with a loop around the measurement and sending out average of 3 good measurements. I use Mongoose OS on all my nodes that connect to my node-red hub using MQTT.
-Anita

1 Like