Help me understand this program and utility with Nodemcu8266?

HEllo again , I am still working with tutorials and nodemcu 8266 ... This time I am following this tutorial .
https://create.arduino.cc/projecthub/pibots555/how-to-connect-dht11-sensor-with-arduino-uno-f4d239

I onlyhave changed the pin to 04 instead of 5 as is in this program though I get this error message, as defined in the program Failed to read from DHT sensor! ... Now I amwondering why its failing to lread the sensor?
I am uploading also the pictures of how I connected the pins and the code I used :slight_smile:

// Import required libraries
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>

// Replace with your network credentials
const char* ssid = "REPLACETHIS";
const char* password = "REPLACETHIS";

#define DHTPIN 4     // Digital pin D1 connected to the DHT sensor

// Uncomment the type of sensor in use:
#define DHTTYPE    DHT11     // DHT 11
//#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

// current temperature & humidity, updated in loop()
float t = 0.0;
float h = 0.0;

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;    // will store last time DHT was updated

// Updates DHT readings every 10 seconds
const long interval = 10000;  

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP8266 DHT Server</h2>
  <p>
    <i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="dht-labels">Temperature</span> 
    <span id="temperature">%TEMPERATURE%</span>
    <sup class="units">°C</sup>
  </p>
  <p>
    <i class="fas fa-tint" style="color:#00add6;"></i> 
    <span class="dht-labels">Humidity</span>
    <span id="humidity">%HUMIDITY%</span>
    <sup class="units">%</sup>
  </p>
  <p>
      <script src="https://apps.elfsight.com/p/platform.js" defer></script>
<div class="elfsight-app-65e091b0-d33c-4191-81f3-be77c921660a"></div>
    </P>
  <p>
    <i class="fab fa-youtube" style="font-size:1.0rem;color:red;"></i>
    <span style="font-size:1.0rem;">Subscribe to </span>
    <a href="https://www.youtube.com/channel/UC49xSqiQ6gBrxUMQ9zvzO6A" target="_blank" style="font-size:1.0rem;">The IoT Projects YouTube Channel</a>
  </P>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperature").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 10000 ) ;

setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("humidity").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/humidity", true);
  xhttp.send();
}, 10000 ) ;
</script>
</html>)rawliteral";

// Replaces placeholder with DHT values
String processor(const String& var){
  //Serial.println(var);
  if(var == "TEMPERATURE"){
    return String(t);
  }
  else if(var == "HUMIDITY"){
    return String(h);
  }
  return String();
}

void setup(){
  // Serial port for debugging purposes
  Serial.begin(115200);
  dht.begin();
  
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }

  // Print ESP8266 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", String(t).c_str());
  });
  server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", String(h).c_str());
  });

  // Start server
  server.begin();
}
 
void loop(){  
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    // save the last time you updated the DHT values
    previousMillis = currentMillis;
    // Read temperature as Celsius (the default)
    float newT = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    //float newT = dht.readTemperature(true);
    // if temperature read failed, don't change t value
    if (isnan(newT)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      t = newT;
      Serial.println(t);
    }
    // Read Humidity
    float newH = dht.readHumidity();
    // if humidity read failed, don't change h value 
    if (isnan(newH)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      h = newH;
      Serial.println(h);
    }
  }
}


I hope you can help me understand this better :slight_smile:

change this to 5. If you really want to learn, it's a good idea to only use code that you understand every word and symbol in, and study the syntax of each line until the code is yours.

1 Like

Thankyou , I replaced with 4 cousew I put in the pin n 04 , why I have to type 5 if the pin used is different and why in the tutorial it says instead to even use the pin 01?
Anyway even replacing with 5 still not working .
Still fails to read from sensor ...

I didn't write the tutorial, or even click on the link. But, if you put the DHT sensor on a pin, you need to reference that pin in the program somehow. I already can tell from this code that I'm not wanting to be inside the author's code. If it is a means to an end, go with it, but if you want to learn to write code, start with a body of code you wrote and build up from there. Tutorial questions should be asked of the author.

Ok I did a further test and apparently the code is fine , the problem is that in the schematics on the tutorial the Vcc and the signal are inverted for some reason , I made reference to the actual dht 11 pin image and inverted the cables, and now all works fine ^ .. .thanks a lot ...

I'm wondering why the code works if you have connected the DHT-Data-pin to the nodeMCU-pin D4 like shown in the picture

and in the code using
either IO-pin 5 or IO-pin 4
because on a nodeMCU-board the IO-pin named on the board "D4" is inside the code IO-pin 2

See also the AZ-delivery pin-out diagram

Be the change you want to see in the world
best regards Stefan

1 Like

For some reason, the NodeMCU designer decided to assign the names D0 through D8 to their digital pins and define them as the GPIO pin number of the pin:

D0 = 6 (GPIO6)
D1 = 5 (GPIO5)
D2 = 4 (GPIO4)
D3 = 0 (GPIO0)
D4 = 2 (GPIO2)
D5 = 14 (GPIO14)
D6 = 12 (GPIO12)
D7 = 13 (GPIO13)
D8 = 15 (GPIO15)

That means you can't refer to the pin with a number unless you, and everyone looking at your code, knows the mapping. I recommend that you always use the labels.

The DHT sensor on Pin D4 should work if you change the line to:
#define DHTPIN D4 // Digital pin D4 connected to the DHT sensor

1 Like

because I inverted :sweat_smile: :see_no_evil:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.