Search code examples
sensorsesp8266arduino-idearduino-esp8266

connect DHT11 to ESP8266


I connect DHT11 to pin D2 ESP8266. Use this code. In the console displays "Read fail". How can I fix it?

DHT11 tested on Arduino, it is working properly.

#include "DHT.h"
#define DHT11PIN D2


DHT dht11(DHT11PIN, DHT11 );


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

  dht11.begin();

}

void loop() {
  delay(2000);
  float h11 = dht11.readHumidity();
  float t11 = dht11.readTemperature();
  float f11 = dht11.readTemperature(true);
}

Solution

  • There is no D2 pin in Esp8266. It is an nodemcu definition. So you can use

    #define DHT11PIN 4
    DHT dht11(DHT11PIN, DHT11 ); 
    

    where D2 is connected to the 4th gpio in Esp8266.

    Or, you can correctly set board type from device manager as NodeMCU and add

    #include "Arduino.h"
    

    to your code.