NodeMcu12E version Interface with DHT11

Dear all,

I finally purchased Nodemcu 12e version . i have tested basic code with this module and updating board manager and library for it.

Code1: Here i am testing the code where turn on LED and Turn off LED using local web server.This is working very welll need clarification in below parts

  1. weather Local Ip address can be set to device or not ? if yes how it can be done in below code
  2. If multiple client trying to aceess common server then it get hangs,
    for example i have connected 2 mobile device to same router . if mob1 con connected to local ip one at time. of both mobile tryint to access common client it will hang, How can i avoid it
#include <ESP8266WiFi.h>

const char* ssid = "esp8266";
const char* password = "Test123456";

int ledPin = 13; // GPIO13
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("

");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a>
");  
  client.println("</html>");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

Code2: For this i am looking for DHT11 library.
If am trying this library gives out error https://roboindia.com/tutorials/DHT11-NodeMCU-arduino Node MCU not supporting these library

if i use DHT11 library like in arduino uno it will work. but same library wont supported for Nodemcu.
Is there any simple coding. It detected and display same server.

  1. weather Local Ip address can be set to device or not ? if yes how it can be done in below code

You can provide a fixed IP address to the WiFi object by using the config method (WiFi.config(IP, gateway, subnet,dns)).

f both mobile tryint to access common client it will hang, How can i avoid it

By not accessing the ESP directly but by a server which serializes the access the ESP.

if i use DHT11 library like in arduino uno it will work. but same library wont supported for Nodemcu.

The Adafruit DHT library should work on ESPs. If you still have problems this library is designed for ESPs.

why cant i able to access multiple mobile accessing at same time.if multiple mobile access same ip adress at same it will hangs.

Like wise arduino uno , weather watch dog timer available or not.

How to use serial communication on Node MCU E version. It has 2 uart how it can be used any sample code available.

why cant i able to access multiple mobile accessing at same time.if multiple mobile access same ip adress at same it will hangs.

Put a caching server in front of it as I wrote in my last answer. An IoT device is not designed to serve multiple clients concurrently.

Like wise arduino uno , weather watch dog timer available or not.

I don't know what you're trying to say with this.

with Below code i used to get timeout error.Below code is without any library function.

// DHT11 and DHT22 sensor reading demo
// by 'jurs' for Arduino Forum

// DHT functions enumerated
enum {DHT11_SAMPLE, DHT22_SAMPLE, DHT_TEMPERATURE, DHT_HUMIDITY, DHT_DATAPTR};

// Begin of user configuration area
#define DHT_SAMPLE DHT11_SAMPLE // must be DHT11_SAMPLE or DHT22_SAMPLE
#define DHT_PIN 2
// End of user configuration area

// DHT error codes enumerated
enum {DHT_OK=0, DHT_ERROR_TIMEOUT=-1, DHT_ERROR_CRC=-2, DHT_ERROR_UNKNOWN=-3};

void setup()
{
  Serial.begin(115200);
  Serial.println("DHT Temperature and Huminity Measurement");
}

// DHT sensor pinout from left to right looking at the gridded side
// 1-VCC  2-DATA  3-NC  4-GND

int dhtCall(byte pin, byte function)
// input parameters are the data pin and one of the DHT functions
// return value is DHT error code with function DHT11_SAMPLE or DHT22_SAMPLE
// alsways do sampling with DHT_OK result before calling other functions
// return value is temperature with function DHT_TEMPERATURE
// return value is humidity with function DHT_HUMIDITY
// return value is pointer to byte array containing raw data with function DHT_DATAPTR
{
  static int temperature=-999;
  static int humidity=-999;
  static byte data[5]; // 5 bytes to receive 40 data bits
  unsigned int loopCnt; // loop counter
  byte sum;  // checksum
  #define DHT_LOOPS 1800
  int triggerTime;
  switch (function)
  {
    case DHT11_SAMPLE: // REQUEST DHT11 SAMPLE
    case DHT22_SAMPLE: // REQUEST DHT22 SAMPLE
      if (function==DHT11_SAMPLE) triggerTime=20000; // 20000µs trigger time for DHT11
      else triggerTime=1000; // 1000µs trigger time for DHT22
      pinMode(pin, OUTPUT); 
      digitalWrite(pin, LOW);
      delayMicroseconds(triggerTime); 
      pinMode(pin,INPUT_PULLUP);
      loopCnt = DHT_LOOPS;
      while(digitalRead(pin) == HIGH) if (loopCnt-- == 0) return DHT_ERROR_TIMEOUT;
      loopCnt = DHT_LOOPS;
      while(digitalRead(pin) == LOW) if (loopCnt-- == 0) return DHT_ERROR_TIMEOUT;
      loopCnt = DHT_LOOPS;
      while(digitalRead(pin) == HIGH) if (loopCnt-- == 0) return DHT_ERROR_TIMEOUT;
      for (byte bitNum=0;bitNum<40;bitNum++) // try reading 40 bits
      {
        loopCnt = DHT_LOOPS;
        while(digitalRead(pin) == LOW) if (loopCnt-- == 0) return DHT_ERROR_TIMEOUT;
        delayMicroseconds(32);
        boolean dhtBit=digitalRead(pin);
        bitWrite(data[bitNum/8],7-bitNum%8,dhtBit);
        loopCnt = DHT_LOOPS;
        while(digitalRead(pin) == HIGH) if (loopCnt-- == 0) return DHT_ERROR_TIMEOUT;
      }
      sum = data[0] + data[1] + data[2] + data[3];  
      if (data[4] != sum) return DHT_ERROR_CRC;
      if (function==DHT11_SAMPLE)
      {
        humidity=data[0];
        temperature=data[2];
      }
      else
      {
        humidity=data[0]*256+data[1];
        temperature= (data[2] & 0x7F) * 256 + data[3];
        if (data[2] & 0x80) temperature= -temperature;
      }
      return DHT_OK;
    case DHT_TEMPERATURE:
      return temperature;
    case DHT_HUMIDITY:  
      return humidity;
    case DHT_DATAPTR:
      return (int)data;
    default:
      return DHT_ERROR_UNKNOWN;
  }  
}

void loop()
{
  byte* b; // byte pointer for showing raw data
  switch (dhtCall(DHT_PIN, DHT_SAMPLE)) // always request a sample first
  {
    case DHT_OK: // only if DHT_OK is true, get temperature, humidity and possibly raw data
      Serial.print("Humidity: ");
      Serial.print(dhtCall(DHT_PIN, DHT_HUMIDITY));
      Serial.print("   Temp: ");
      Serial.print(dhtCall(DHT_PIN, DHT_TEMPERATURE));
      Serial.print("     raw data:  ");
      b=(byte*)dhtCall(DHT_PIN, DHT_DATAPTR);
      for (int i=0;i<5;i++)
      {
        Serial.print(b[i]);Serial.print('\t');
      }
      Serial.println();
      break;
    case DHT_ERROR_TIMEOUT:
      Serial.println("Timeout Error");
      break;
    case DHT_ERROR_CRC:
      Serial.println("CRC Error");
      break;
    default:
      Serial.println("Unknown Error");
  }
  delay(2000); // minimum time between two DHT samples is two seconds
}

I have tested code like Below and Its started working
Hope It will Help others.

#include "DHT.h"

DHT dht;

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)");

  dht.setup(D3);   /* D1 is used for data communication */
}

void loop()
{
  delay(dht.getMinimumSamplingPeriod());  /* Delay of amount equal to sampling period */

  float humidity = dht.getHumidity(); /* Get humidity value */
  float temperature = dht.getTemperature(); /* Get temperature value */

  Serial.print(dht.getStatusString());  /* Print status of communication */
  Serial.print("\t");
  Serial.print(humidity, 1);
  Serial.print("\t\t");
  Serial.print(temperature, 1);
  Serial.print("\t\t");
  Serial.println(dht.toFahrenheit(temperature), 1);
delay(1000);

  
}
#include "DHT.h"

void DHT::setup(uint8_t pin, DHT_MODEL_t model)
{
  DHT::pin = pin;
  DHT::model = model;
  DHT::resetTimer(); // Make sure we do read the sensor in the next readSensor()

  if ( model == AUTO_DETECT) {
    DHT::model = DHT22;
    readSensor();
    if ( error == ERROR_TIMEOUT ) {
      DHT::model = DHT11;
      // Warning: in case we auto detect a DHT11, you should wait at least 1000 msec
      // before your first read request. Otherwise you will get a time out error.
    }
  }
}

void DHT::resetTimer()
{
  DHT::lastReadTime = millis() - 3000;
}

float DHT::getHumidity()
{
  readSensor();
  return humidity;
}

float DHT::getTemperature()
{
  readSensor();
  return temperature;
}

#ifndef OPTIMIZE_SRAM_SIZE

const char* DHT::getStatusString()
{
  switch ( error ) {
    case DHT::ERROR_TIMEOUT:
      return "TIMEOUT";

    case DHT::ERROR_CHECKSUM:
      return "CHECKSUM";

    default:
      return "OK";
  }
}

#else

// At the expense of 26 bytes of extra PROGMEM, we save 11 bytes of
// SRAM by using the following method:

prog_char P_OK[]       PROGMEM = "OK";
prog_char P_TIMEOUT[]  PROGMEM = "TIMEOUT";
prog_char P_CHECKSUM[] PROGMEM = "CHECKSUM";

const char *DHT::getStatusString() {
  prog_char *c;
  switch ( error ) {
    case DHT::ERROR_CHECKSUM:
      c = P_CHECKSUM; break;

    case DHT::ERROR_TIMEOUT:
      c = P_TIMEOUT; break;

    default:
      c = P_OK; break;
  }

  static char buffer[9];
  strcpy_P(buffer, c);

  return buffer;
}

#endif

void DHT::readSensor()
{
  // Make sure we don't poll the sensor too often
  // - Max sample rate DHT11 is 1 Hz   (duty cicle 1000 ms)
  // - Max sample rate DHT22 is 0.5 Hz (duty cicle 2000 ms)
  unsigned long startTime = millis();
  if ( (unsigned long)(startTime - lastReadTime) < (model == DHT11 ? 999L : 1999L) ) {
    return;
  }
  lastReadTime = startTime;

  temperature = NAN;
  humidity = NAN;

  // Request sample

  digitalWrite(pin, LOW); // Send start signal
  pinMode(pin, OUTPUT);
  if ( model == DHT11 ) {
    delay(18);
  }
  else {
    // This will fail for a DHT11 - that's how we can detect such a device
    delayMicroseconds(800);
  }

  pinMode(pin, INPUT);
  digitalWrite(pin, HIGH); // Switch bus to receive data

  // We're going to read 83 edges:
  // - First a FALLING, RISING, and FALLING edge for the start bit
  // - Then 40 bits: RISING and then a FALLING edge per bit
  // To keep our code simple, we accept any HIGH or LOW reading if it's max 85 usecs long

  uint16_t rawHumidity = 0;
  uint16_t rawTemperature = 0;
  uint16_t data = 0;

  for ( int8_t i = -3 ; i < 2 * 40; i++ ) {
    byte age;
    startTime = micros();

    do {
      age = (unsigned long)(micros() - startTime);
      if ( age > 90 ) {
        error = ERROR_TIMEOUT;
        return;
      }
    }
    while ( digitalRead(pin) == (i & 1) ? HIGH : LOW );

    if ( i >= 0 && (i & 1) ) {
      // Now we are being fed our 40 bits
      data <<= 1;

      // A zero max 30 usecs, a one at least 68 usecs.
      if ( age > 30 ) {
        data |= 1; // we got a one
      }
    }

    switch ( i ) {
      case 31:
        rawHumidity = data;
        break;
      case 63:
        rawTemperature = data;
        data = 0;
        break;
    }
  }

  // Verify checksum

  if ( (byte)(((byte)rawHumidity) + (rawHumidity >> 8) + ((byte)rawTemperature) + (rawTemperature >> 8)) != data ) {
    error = ERROR_CHECKSUM;
    return;
  }

  // Store readings

  if ( model == DHT11 ) {
    humidity = rawHumidity >> 8;
    temperature = rawTemperature >> 8;
  }
  else {
    humidity = rawHumidity * 0.1;

    if ( rawTemperature & 0x8000 ) {
      rawTemperature = -(int16_t)(rawTemperature & 0x7FFF);
    }
    temperature = ((int16_t)rawTemperature) * 0.1;
  }

  error = ERROR_NONE;
}

DHT11.h

#ifndef dht_h
#define dht_h

#if ARDUINO < 100
  #include <WProgram.h>
#else
  #include <Arduino.h>
#endif

class DHT
{
public:

  typedef enum {
    AUTO_DETECT,
    DHT11,
    DHT22,
    AM2302,  // Packaged DHT22
    RHT03    // Equivalent to DHT22
  }
  DHT_MODEL_t;

  typedef enum {
    ERROR_NONE = 0,
    ERROR_TIMEOUT,
    ERROR_CHECKSUM
  }
  DHT_ERROR_t;

  void setup(uint8_t pin, DHT_MODEL_t model=AUTO_DETECT);
  void resetTimer();

  float getTemperature();
  float getHumidity();

  DHT_ERROR_t getStatus() { return error; };
  const char* getStatusString();

  DHT_MODEL_t getModel() { return model; }

  int getMinimumSamplingPeriod() { return model == DHT11 ? 1000 : 2000; }

  int8_t getNumberOfDecimalsTemperature() { return model == DHT11 ? 0 : 1; };
  int8_t getLowerBoundTemperature() { return model == DHT11 ? 0 : -40; };
  int8_t getUpperBoundTemperature() { return model == DHT11 ? 50 : 125; };

  int8_t getNumberOfDecimalsHumidity() { return 0; };
  int8_t getLowerBoundHumidity() { return model == DHT11 ? 20 : 0; };
  int8_t getUpperBoundHumidity() { return model == DHT11 ? 90 : 100; };

  static float toFahrenheit(float fromCelcius) { return 1.8 * fromCelcius + 32.0; };
  static float toCelsius(float fromFahrenheit) { return (fromFahrenheit - 32.0) / 1.8; };

protected:
  void readSensor();

  float temperature;
  float humidity;

  uint8_t pin;

private:
  DHT_MODEL_t model;
  DHT_ERROR_t error;
  unsigned long lastReadTime;
};

#endif /*dht_h*/

I have put below code into local web.

  1. LED trigger will take long time. without DHT11 data read it reply Fast
    2)How can i use Local Ip in below code
    3)How Autorefresh of data can be made.
#include <ESP8266WiFi.h>
#include "DHT.h"

DHT dht;
 
const char* ssid = "esp8266";
const char* password = "Test123456";
 
int ledPin = 13; // GPIO13
WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
  delay(10);
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  dht.setup(D3);   /* D1 is used for data communication */
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");
 
  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
 
}
 
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }


// New code has been added 

 delay(dht.getMinimumSamplingPeriod());  /* Delay of amount equal to sampling period */

  float humidity = dht.getHumidity(); /* Get humidity value */
  float temperature = dht.getTemperature(); /* Get temperature value */

 // Serial.print(dht.getStatusString());  /* Print status of communication */

  
 
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
 
  // Match the request
 
  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
    digitalWrite(ledPin, HIGH);
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
    digitalWrite(ledPin, LOW);
    value = LOW;
  }
 
// Set ledPin according to the request
//digitalWrite(ledPin, value);
 
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");
 
  client.print("Led pin is now: ");
 
  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("

");
  client.println("<a href=\"/LED=ON\"\"><button>Turn On </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Turn Off </button></a>
");  
  client.println("</html>");

  client.println("DHT11_HumidityReading: ");
  client.println(humidity,1);
   client.println("

");
  client.println("DHT11_Temprature Reading: ");
  client.println(temperature,1);
   client.println("

");
  

  
 
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
 
}