I am trying to read temp and humidity values from DHT sensor and want to see these readings on Blynk mobile app and serial monitor but it’s not reading the value and every time only if statement is running, so it shows “Failed to read from DHT sensor” . Please figure out what may be the issue and help me out with this code!
#define BLYNK_TEMPLATE_ID "*************"
#define BLYNK_TEMPLATE_NAME "**********"
#define BLYNK_AUTH_TOKEN "***********"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <Wire.h>
#include <DHT.h>
#define DHTTYPE DHT11
#define DHTPIN 4
DHT dht(DHTPIN, DHTTYPE); //(sensor pin,sensor type)
char auth[] = "*********"; //Enter the Auth code which was send by Blink
char ssid[] = "******"; //Enter your WIFI Name
char pass[] = "******"; //Enter your WIFI Password
BlynkTimer timer;
void sendSensor() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Blynk.virtualWrite(V0, t);
Blynk.virtualWrite(V1, h);
Serial.print("Temperature : ");
Serial.println(t);
Serial.print("Humidity : ");
Serial.println(h);
delay(1000);
}
void setup() {
Serial.begin(115200);
Blynk.begin(auth, ssid, pass);
dht.begin();
timer.setInterval(100L, sendSensor);
}
void loop() {
Blynk.run();
timer.run();
delay(1000);
}
You need to remove these two delays and change the timer interval from 100L to at least 2000L.
You can’t use blocking delays with Blynk, and the DHT11 sensor is very sow and doesn’t respond well to be ing read more than once every two seconds.
If that doesn’t resolve your issue then you need to provide more information about what board type you are using, exactly which type of DHT11 sensor you have, and exactly how you’ve connected your sensor to your board.
Using this line of code, you can call a function at preset intervals like 1sec or 1min and so on.
For DTH it needs more time to throw the readings. If you call the read function too quickly, it will not return any readings. You can set an interval of minimum 2min for optimal readings.
Reading temperature too ofter is not required, as its not going to fluctuate too frequently unless its a hot furnace.
When I changed my code based on your inputs, the code was running for few seconds perfectly but after that again it’s showing “Failed to read from Dht sensor”
The number (100 Long Integer in your original code) is the frequency in milliseconds that the function (sendSensor in this case) will be executed. You’re calling this function 10 times per second, but the sensor doesn’t like it if you do more than once every 2 seconds.