ESP8266 and DHT11 - unstable reading

I did a humidity and temperature sensor based on ESP8266 and DHT11 and the power of the charger from the phone. Unfortunately, the next consecutive readings are very unstable - the temperature jumps of +/- 2st and humidity +/- 5%. After connecting the sensor DHT11 the Arduino Mega2650 results are stable. Adding a capacitor did not help.
Have I committed an error in the code below if problems are caused by something else?

/* ESP8266 + MQTT Humidity and Temperature Node
 */

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

const char* ssid = "siec";
const char* password = "pass";
const char* mqtt_server = "192.168.1.5";

#define DHTTYPE DHT11 // DHT11 or DHT22
#define DHTPIN  2

DHT dht(DHTPIN, DHTTYPE,11);

WiFiClient espClient;
PubSubClient client(espClient);

void setup()  /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(115200);
  dht.begin();   
  // setup WiFi
  setup_wifi(); 
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid); 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  WiFi.config(IPAddress(192,168,1,*), IPAddress(192,168,1,*), IPAddress(255,255,255,0));
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  Serial.println("");
  Serial.println("WiFi connected"); 
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client0")) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void loop() {
    if (!client.connected()) {
    reconnect();
  }
  client.loop();

  delay(2000);
     
    float h = dht.readHumidity();
    float t = dht.readTemperature();
   
    h = h*1.0;  //to jest jakas korekta
    t = t*1.0;  // jak skazowałem to dht nie dawal wyników
   
    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t)) {
      Serial.println("Blad odczytu z DHT!");
    }
    else
    {
      char* tPayload = f2s(t,0);
      char* hPayload = f2s(h,0);
           
      Serial.println(tPayload);
      client.publish("/salon/temp/", tPayload);
//      delay(10000);
      Serial.println(hPayload);
      client.publish("/salon/wilgoc/", hPayload);
      delay(15000);
    }   
  }

/* float to string
 * f is the float to turn into a string
 * p is the precision (number of decimals)
 * return a string representation of the float.
 */
char *f2s(float f, int p){
  char * pBuff;                         // use to remember which part of the buffer to use for dtostrf
  const int iSize = 10;                 // number of buffers, one for each float before wrapping around
  static char sBuff[iSize][20];         // space for 20 characters including NULL terminator for each float
  static int iCount = 0;                // keep a tab of next place in sBuff to use
  pBuff = sBuff[iCount];                // use this buffer
  if(iCount >= iSize -1){               // check for wrap
    iCount = 0;                         // if wrapping start again and reset
  }
  else{
    iCount++;                           // advance the counter
  }
  return dtostrf(f, 0, p, pBuff);       // call the library function
}

void messageReceived(String topic, String payload, char * bytes, unsigned int length) {
  Serial.print("incoming: ");
  Serial.print(topic);
  Serial.print(" - ");
  Serial.print(payload);
  Serial.println();
}

@sliver001,I use a very similar setup, and my temperature readings appear to be spot-on, with very little fluctuation. The only difference is I’m using a DHT22 sensor, which is slightly more precise.

Looking at your code, the DHT dht(DHTPIN, DHTTYPE,11); declaration appears incorrect (I have DHT dht(DHTPIN, DHTTYPE); in my version. Which version of the DHT library are you using? Mine is 1.2.1 from Adafruit.

I also use deepsleep (with pin D0 connected to RST), and just turn the sensor on once every minute to send the reading to my mqtt server.

Try changing that declaration, and see if it works. I’ll post my code below, in case you want to see if it works any different.

P.S. Pozdrawiam!

// ESP8266 DHT22 over MQTT

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

/************ WIFI and MQTT INFORMATION (CHANGE THESE FOR YOUR SETUP) ******************/
#define wifi_ssid "ssid" //enter your WIFI SSID
#define wifi_password "pass" //enter your WIFI Password

#define mqtt_server "mqttserver" // Enter your MQTT server address or IP.
#define mqtt_device "device" //MQTT device
#define mqtt_user "" //enter your MQTT username
#define mqtt_password "" //enter your password

/****************************** MQTT TOPICS (change these topics as you wish)  ***************************************/

#define temperaturepub "home/sensor1/temperature"
#define humiditypub "home/sensor1/humidity"
#define tempindexpub "home/sensor1/temperatureindex"

/*****************************************************/

#define DHTPIN 4     // what digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();

  setup_wifi();

  client.setServer(mqtt_server, 1883); //CHANGE PORT HERE IF NEEDED
  
}

void setup_wifi() {

  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

 if (!client.loop()) {
  reconnect();
 }
  
  
  // 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 set invalid values if so.
  if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
h=t=f=-1;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  char strCh[10];
  
  String str = String(f,2);
  str.toCharArray(strCh,9);
  client.publish(temperaturepub, strCh);
  str = String(h,2);
  str.toCharArray(strCh,9);
  client.publish(humiditypub, strCh);
  str = String(hif,2);
  str.toCharArray(strCh,9);
  client.publish(tempindexpub, strCh);
  
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");

// Wait a few seconds between measurements.
  ESP.deepSleep(60000000,WAKE_RF_DEFAULT); //60 second delay
}


void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
  if (client.connect(mqtt_device, mqtt_user, mqtt_password)) {
  Serial.println("connected");

  client.subscribe(temperaturepub);
  client.subscribe(humiditypub);
  client.subscribe(tempindexpub);
} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  // Wait 5 seconds before retrying
  delay(5000);
}
  }
}

Unfortunately, its code is the same - moisture readings every 39 and in a moment 46%. The code information is read for the old sensor 2 seconds - how to enable it?

P.S.
Również pozdrawiam :slight_smile:

I wonder if the DHT11 is just not precise enough for your application. Maybe try extending the sleep timer to 3 seconds in your code? It’s possible that you’re taking readings too often, causing instability in the sensor. I definitely have no issues with my code, but I’m using DHT22 and taking readings every 60 seconds…

Use ESPEasy. Its working like a charm.