You are here

Multiple DHT humidity sensors on Arduino

A reader of my book Arduino Projects To Save The World recently asked me about the DHT11 and DHT22 sensors. In particular, how to connect multiple sensors (and how to write the code for it) to an Arduino. I must admit I had never considered it. I have used them plenty of times, but not in parallel. Turns out, Adafruit's DHT library makes it super easy. Just repeate the wiring diagram for each sensor, connecting the data pin to any digital pin available, one pin per sensor. In the example below, I chose pins 2 and 3.

The DHT command creates the object, and we can give any name we want to it. So, in the code DHT dht1(DHT1PIN, DHT1TYPE);  'dht1' is the name I chose, but could easily be 'inside' or 'outside.' And the variables can be similarly named: DHT outsideDHT(outsidePin, outsideType); would be fine.

The following example was tested with Arduino V1.0.5, a DHT11 and a DHT22 running together:

 

 

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
 
// DHT_dual_test
// Demonstrates multiple sensors
// Modified sketch by DIY-SciB.org
 
#include "DHT.h"
 
#define DHT1PIN 2     // what pin we're connected to
#define DHT2PIN 3
 
// Uncomment whatever type you're using!
#define DHT1TYPE DHT11   // DHT 11 
#define DHT2TYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
 
// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
 
DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);
 
void setup() {
  Serial.begin(9600); 
  Serial.println("DHTxx test!");
 
  dht1.begin();
  dht2.begin();
}
 
void loop() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h1 = dht1.readHumidity();
  float t1 = dht1.readTemperature();
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();
 
  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t1) || isnan(h1)) {
    Serial.println("Failed to read from DHT #1");
  } else {
    Serial.print("Humidity 1: "); 
    Serial.print(h1);
    Serial.print(" %\t");
    Serial.print("Temperature 1: "); 
    Serial.print(t1);
    Serial.println(" *C");
  }
  if (isnan(t2) || isnan(h2)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print("Humidity 2: "); 
    Serial.print(h2);
    Serial.print(" %\t");
    Serial.print("Temperature 2: "); 
    Serial.print(t2);
    Serial.println(" *C");
  }
  Serial.println();
}

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer