DHT22 not updating?

Hi All,

I have an Arduino and Ethernet shield I have been playing with, which is interfaced with a light sensor (Analogue) and a DHT22. I plan on mounting the entire thing in a case and using it in my greenhouse to work out the temperature, humidity and light. So anyway long story short, I have it all set up with so i can connect to the device and the webpage is shown below, each time i connect the light changes which is fine, but the temperature and humidity remain the same.

I have a few server begin lines repeated to try and prevent any issues with the server starting, but could someone take a look below and let me know if i have missed something, or put the code in the wrong place preventing the temp and humidity from being updated and polled each time the browser is visited. Basically what i was / am trying to achieve is that each time the page is visited, it will be updated with the latest temperature, humidity and light measurements.

/*
 
 http://www.bajdi.com
 
 Web  Server showing the values from a DHT22 sensor
 */

#include <SPI.h>
#include <Ethernet.h>
#include <dht.h>

dht DHT;

#define DHTTYPE DHT22  // Sensor type
#define DHT22_PIN 4    // Data pin of DHT22 sensor
int lightLevel; 


byte mac[]     = { 0x00, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[]	= { 192, 168, 1, 179 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[]  = { 255, 255, 255, 0 };
EthernetServer server(80);
 

void setup()
{

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  delay(1000);
  server.begin();
  delay(1000);
  server.begin();
}

void loop()
{
  int chk = DHT.read22(DHT22_PIN);
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        lightLevel = analogRead(A0);
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();


          // output the value of the DHT22 sensor
          client.print("Arduino powered webserver");
          client.println("#
");
          client.print("Serving temperature and humidity values from a DHT22 sensor");
          client.println("#
");
          client.print("Light : ");
          client.print(lightLevel);
          client.println(" #
");
          client.print("Temperature (oC): ");
          client.print(DHT.temperature);
          client.println(" #
");
          client.print("Humidity (%): ");
          client.print(DHT.humidity);
          client.println(" #
");

          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(90);
    // close the connection:
    client.stop();
  }
}

With the above code, a website is created as above;

Arduino powered webserver#
Serving temperature and humidity values from a DHT22 sensor#
Light : 57 #
Temperature (oC): 21.70 #
Humidity (%): 69.80 #
  server.begin();
  delay(1000);
  server.begin();
  delay(1000);
  server.begin();

What? Why is server.begin() called three times? What issue are you trying to solve here?

So anyway long story short, I have it all set up with so i can connect to the device and the webpage is shown below, each time i connect the light changes which is fine, but the temperature and humidity remain the same.

In the sketch you wrote to test the DHT22 without the web stuff, did the DHT22 work? What are you doing to change the temperature or humidity that the sensor sees? Is the value that it is reporting wrong? Where did you get the dht library that you are using?

The DHT22 needs 2 seconds between reads, your loop is too tight, so try this variation…
(code not tested, small bugs may have entered :slight_smile:

/*
 
 http://www.bajdi.com
 
 Web  Server showing the values from a DHT22 sensor
 */

#include <SPI.h>
#include <Ethernet.h>
#include <dht.h>

dht DHT;

#define DHTTYPE DHT22  // Sensor type
#define DHT22_PIN 4       // Data pin of DHT22 sensor

int lightLevel; 
int temp;
int humi;

byte mac[]     = { 0x00, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[]	= { 192, 168, 1, 179 };
byte gateway[] = { 192, 168, 1, 1 };
byte subnet[]  = { 255, 255, 255, 0 };

EthernetServer server(80);

unsigend long lastTime = 0;

void setup()
{
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  delay(2000);
  
}

void loop()
{
  // DHT measurements, max once per 2 seconds
  if (millis() - 2000 > lastTime)
  {
    lastTime += 2000;
    int chk = DHT.read22(DHT22_PIN);
    temp = DHT.temperature;
    humi = DHT.humidity;
  }
  // multiple analog reads smooths the signal
  lightLevel = 0;
  for (int i=0; i<16; i++) lightLevel += analogRead(A0);
  lightLevel /= 16;


  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) 
  {
    boolean currentLineIsBlank = true;
    while (client.connected()) 
    {
      if (client.available()) 
      {
        char c = client.read();
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) 
        {
          response();
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(90);
    // close the connection:
    client.stop();
  }
}


// just to keep all output together
void response()
{
  // send a standard http response header
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();

  // output the value of the DHT22 sensor  
  client.print("Arduino powered webserver");
  client.println("#
");
  client.print("Serving temperature and humidity values from a DHT22 sensor");
  client.println("#
");
  client.print("Light : ");
  client.print(lightLevel);
  client.println(" #
");
  client.print("Temperature (oC): ");
  client.print(temp);
  client.println(" #
");
  client.print("Humidity (%): ");
  client.print(humi);
  client.println(" #
");
}

I was having trouble with the ethernet shield not responding, which i think was a problem with the reset issue rather than anything else so that problem was solved by putting a capacitor and resistor in between VCC, reset and Gnd and the web server works fine.

Ignoring the multiple begin, which i will strip out of the next version of the sketch the problem I am having is that the web server works fine but the temperature and humidity stay as the same value whenever i visit the page.

Below are the dht.c and dht.h files, I am new to this and a bit confused, I did try a different demo which sent the temperature, light and humidity to the serial port which worked well, I found another demo which was the sketch i used and wanted to have the webpage be updated with the temperature, light and humidity when the client accesses it. The problem is the light varies which is good, but the temperature and humidity remain constant, for some reason it is like the DHT22 is not being updated or queried, its almost as if it gets accessed when the device starts up, and sets the temperature and humidity, and remains that way, so each time the page is accessed it just feeds back the same variable it stored at the start, rather than getting a new temperature and humidity.

Apologies if that does not make sense.

//
//    FILE: dht.cpp
// VERSION: 0.1.01
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
//
// DATASHEET: 
//
// HISTORY:
// 0.1.01 added support for Arduino 1.0, fixed typos (31/12/2011)
// 0.1.0 by Rob Tillaart (01/04/2011)
// inspired by DHT11 library
//

#include "dht.h"

#define TIMEOUT 10000

/////////////////////////////////////////////////////
//
// PUBLIC
//


// return values:
//  0 : OK
// -1 : checksum error
// -2 : timeout
int dht::read11(uint8_t pin)
{
	// READ VALUES
	int rv = read(pin);
	if (rv != 0) return rv;

	// CONVERT AND STORE
	humidity    = bits[0];  // bit[1] == 0;
	temperature = bits[2];  // bits[3] == 0;

	// TEST CHECKSUM
	uint8_t sum = bits[0] + bits[2]; // bits[1] && bits[3] both 0
	if (bits[4] != sum) return -1;

	return 0;
}

// return values:
//  0 : OK
// -1 : checksum error
// -2 : timeout
int dht::read22(uint8_t pin)
{
	// READ VALUES
	int rv = read(pin);
	if (rv != 0) return rv;

	// CONVERT AND STORE
	humidity    = word(bits[0], bits[1]) * 0.1;

	int sign = 1;
	if (bits[2] & 0x80) // negative temperature
	{
		bits[2] = bits[2] & 0x7F;
		sign = -1;
	}
	temperature = sign * word(bits[2], bits[3]) * 0.1;


	// TEST CHECKSUM
	uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];
	if (bits[4] != sum) return -1;

	return 0;
}

/////////////////////////////////////////////////////
//
// PRIVATE
//

// return values:
//  0 : OK
// -2 : timeout
int dht::read(uint8_t pin)
{
	// INIT BUFFERVAR TO RECEIVE DATA
	uint8_t cnt = 7;
	uint8_t idx = 0;

	// EMPTY BUFFER
	for (int i=0; i< 5; i++) bits[i] = 0;

	// REQUEST SAMPLE
	pinMode(pin, OUTPUT);
	digitalWrite(pin, LOW);
	delay(20);
	digitalWrite(pin, HIGH);
	delayMicroseconds(40);
	pinMode(pin, INPUT);

	// GET ACKNOWLEDGE or TIMEOUT
	unsigned int loopCnt = TIMEOUT;
	while(digitalRead(pin) == LOW)
		if (loopCnt-- == 0) return -2;

	loopCnt = TIMEOUT;
	while(digitalRead(pin) == HIGH)
		if (loopCnt-- == 0) return -2;

	// READ THE OUTPUT - 40 BITS => 5 BYTES
	for (int i=0; i<40; i++)
	{
		loopCnt = TIMEOUT;
		while(digitalRead(pin) == LOW)
			if (loopCnt-- == 0) return -2;

		unsigned long t = micros();

		loopCnt = TIMEOUT;
		while(digitalRead(pin) == HIGH)
			if (loopCnt-- == 0) return -2;

		if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
		if (cnt == 0)   // next byte?
		{
			cnt = 7;   
			idx++;      
		}
		else cnt--;
	}

	return 0;
}
//
// END OF FILE
//
// 
//    FILE: dht.h
// VERSION: 0.1.01
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
//
//     URL: http://arduino.cc/playground/Main/DHTLib
//
// HISTORY:
// see dht.cpp file
// 

#ifndef dht_h
#define dht_h

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

#define DHT_LIB_VERSION "0.1.01"

class dht
{
public:
	int read11(uint8_t pin);
    int read22(uint8_t pin);
	double humidity;
	double temperature;

private:
	uint8_t bits[5];  // buffer to receive data
	int read(uint8_t pin);
};
#endif
//
// END OF FILE
//

Thanks for your help with the loop suggestion, I will give that a go first thing in the morning. I don’t know why but in my head i did not consider the loop as i was thinking it would only be fired if the web client connected, which would be something like once every 5 minutes, rather than thinking the loop constantly ran. Good point, i will try with the extended time and smoothing the analogue input.

Once again thanks for your help!

Hi Guys,

Thanks for your help with the above, I am having a problem with getting the DHT22 to get a value put in the variables in some code example. Basically i am trying to be able to query the Arduino through USB / Serial to ask for the temperature (c), Humidity (%) or temperature (f) and have it respond with the appropriate value.

I thought the best way to do this would be to have the loop running waiting for the request for Temperature or humidity through the serial monitor and then query that through void response which would query the DHT22 and return the response as an integer.

I had tried without the void response and it did not respond to serial queries, when i have it set so it calls a void response it does run, but the values are not updated or correct, the code is below, as is the serial monitor output:

#include <SPI.h>
#include <dht.h>
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
dht DHT;
#define DHTTYPE DHT22  // Sensor type
#define DHT22_PIN 4       // Data pin of DHT22 sensor

int temp;
int humi;
int tempF;
unsigned long lastTime = 0;

void setup() {
    Serial.begin(9600);
    Serial.write("Power On\n");
}

char Comp(char* This) {
    while (Serial.available() > 0) // Don't read unless
                                   // there you know there is data
    {
        if(index < 19) // One less than the size of the array
        {
            inChar = Serial.read(); // Read a character
            inData[index] = inChar; // Store it
            index++; // Increment where to write next
            inData[index] = '\0'; // Null terminate the string
        }
    }

    if (strcmp(inData,This)  == 0) {
        for (int i=0;i<19;i++) {
            inData[i]=0;
        }
        index=0;
        return(0);
    }
    else {
        return(1);
    }
}

void response() {
     if (millis() - 2000 > lastTime)
  {
    lastTime += 2000;
    Serial.write("Checking DHT22 for Temperature and Humidity\n");
    int chk = DHT.read22(DHT22_PIN);
    Serial.write("(DHT) Int chk: ");
    Serial.write(chk);
    Serial.write("\n");
    temp = DHT.temperature;
    humi = DHT.humidity;
    Serial.write("(DHT) Temperature: ");
    Serial.write(DHT.temperature);    
    Serial.write("\n");    
    Serial.write("(DHT) Humidity: ");
    Serial.write(DHT.humidity);
    Serial.write("\n");
    tempF =(temp * 9/5 + 32);
    Serial.write("Temperature: ");
    Serial.write(temp);
    Serial.write("\n");
    Serial.write("Humidity: ");
    Serial.write(humi);
    Serial.write("\n");

  }
  }
  

void loop()
  
{
    
     if (Comp("tempC")==0) {
        response();
        Serial.write("Temperature (C):");
        Serial.write(temp);
        Serial.write("\n");

    }
    
    if (Comp("tempF")==0) {
        response();
        Serial.write("Temperature (F):");
        Serial.write(tempF);
        Serial.write("\n");
    }
    
    if (Comp("Humidity")==0) {
        response();
        Serial.write("Humidity (%):");
        Serial.write(humi);
        Serial.write("\n");
    }
     
}

When i had the code, and tried the various calls through the serial monitor this was the response:

Power On
Checking DHT22 for Temperature and Humidity
(DHT) Int chk: ÿ
(DHT) Temperature: 
(DHT) Humidity: 9
Temperature: 
Humidity: 9
Temperature (C):
Checking DHT22 for Temperature and Humidity
(DHT) Int chk:

Appreciate any pointers or tips you could give me, id like to get some form of a template or idea on how to best handle using the serial port to make function / void calls to do various things, so the Arduino becomes an interface between the PC and various devices.

Thanks!

Try Serial.print()/Serial.println() instead of Serial.write() for debugging messages.