Comment utiliser les capteurs DHT11 et DHT22 avec Arduino

Composants matériels

  1. Capteur DHT11 à 4 broches
  2. Capteur DHT22 / AM2302 à 4 broches
  3. Capteur DHT11 à 3 broches (recommandé)
  4. Capteur DHT22 / AM2302 à 3 broches (recommandé)
  5. Résistance de 5 à 10 kΩ (uniquement pour les capteurs à 4 broches)
  6. Arduino Uno Rev3
  7. Breadbord
  8. Fils
  9. Câble USB type A / B
  10. LCD I2C 16 × 2 caractères (en option)

Comment fonctionnent les capteurs de température et d’humidité DHT11 et DHT22 / AM2302?

Si vous ouvrez un  capteur DHT11  ou  DHT22 / AM2302 , vous verrez qu’il contient deux éléments de détection: un élément de détection d’humidité et un NTC (thermistance).

L’élément de détection d’humidité se compose de deux électrodes avec un substrat de rétention d’humidité entre les deux. Le capteur mesure la résistance entre les électrodes, qui change en fonction de la quantité d’humidité dans l’air.

À l’arrière du capteur, vous trouverez un petit circuit intégré qui mesure et traite le signal analogique. Il stocke également les coefficients d’étalonnage et effectue la conversion analogique-numérique.

Qu’est-ce que l’humidité relative?

Lorsque vous regardez la fiche technique des capteurs DHTxx, vous verrez qu’ils mesurent l’humidité relative (HR) de l’air et non l’humidité absolue. Mais quelle est la différence? L’humidité absolue est la quantité de vapeur d’eau dans l’air (exprimée en g / m³), ​​quelle que soit la température. L’humidité relative  tient  compte de la température.

L’humidité relative est le rapport entre la quantité réelle de vapeur d’eau présente dans l’air et la quantité maximale de vapeur d’eau que l’air peut contenir à une température donnée.

L’air chaud peut contenir plus d’eau que l’air froid. Cela signifie que pour la même quantité de vapeur d’eau dans l’air, l’humidité relative de l’air frais sera plus élevée que celle de l’air chaud. À 100% d’humidité relative, l’air est saturé et atteint son point de rosée.

Spécifications DHT11

Tension de fonctionnement3,3 à 5,5 V
Courant de fonctionnementMesure: 0,3 mA, veille: 60 μA
Plage de mesure d’humidité5 à 95% d’humidité relative ± 5% d’humidité relative
Plage de mesure de température-20 à 60 ° C ± 2 ° C
Protocole de communication1 fil
Période d’échantillonnage> 2 seconds
Dimensions du corps15,5 x 12 x 5,5 mm
Pin dimensionsLongueur de 8 mm, espacement de 2,54 mm
AvantageCoût ultra bas
CoûtVérifiez le prix

Pour plus d’informations, vous pouvez consulter la fiche technique ci-dessous:

Spécifications DHT22 / AM2302

Tension de fonctionnement3,3 à 5,5 V
Courant de fonctionnementMesure: 0,5 mA, veille: 15 μA
Plage de mesure d’humidité0 à 99,9% d’humidité relative ± 2% d’humidité relative
Plage de mesure de température-40 à 80 ° C ± 1 ° C
Protocole de communicationProtocole de bus à 1 fil
Période d’échantillonnage2 secondes
Dimensions du corps25 x 15 x 7 mm, trou de montage ⌀ 3 mm
Pin dimensionsLongueur 7 mm, espacement de 2,54 mm
AvantagePlus précise
CoûtVérifiez le prix

Vous pouvez télécharger la fiche technique du DHT22 / AM2302 ci-dessous:

Notez que l’  AM2302  est simplement une version filaire du capteur DHT22 à 3 fils.

 

q? encoding=UTF8&ASIN=B073TW7V1T&Format= SL250 &ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=makerguides 20&language=en US

Comme vous pouvez le voir, les spécifications du DHT11 et du DHT22 / AM2302 sont assez similaires. La principale différence est que le DHT22 est plus précis et possède une plus grande plage de mesure.

Le DHT11 est un peu plus petit que le DHT22 et est également moins cher.

La bonne chose à propos de ces capteurs est qu’ils sont interchangeables, ce qui signifie que vous pouvez simplement remplacer le DHT11 par un DHT22 ou vice versa, le câblage est exactement le même. Vous n’aurez qu’à faire un petit changement dans la configuration du code, comme vous le verrez plus tard.


Câblage – Connexion DHT11 et DHT22 / AM2302 à Arduino Uno

Les schémas de câblage / schémas ci-dessous vous montrent comment connecter des capteurs de température et d’humidité à 3 ou 4 broches à l’Arduino Uno. Une résistance pull-up de 10 kΩ est nécessaire entre la ligne de signal et 5 V pour s’assurer que le niveau du signal reste élevé par défaut (voir la fiche technique pour plus d’informations).

DHT11-avec-Arduino-UNO-schéma-câblage-schématique
Câblage du capteur de température et d’humidité DHT11 à 4 broches à Arduino Uno
DHT22-avec-Arduino-UNO-schéma-câblage-schématique
Câblage du capteur de température et d’humidité DHT22 à 4 broches à Arduino Uno

Notez que le capteur DHT22 / AM2302 est connecté exactement de la même manière que le DHT11. Les connexions sont également données dans le tableau ci-dessous. J’ai numéroté les broches 1 à 4 de gauche à droite lorsque les trous du capteur sont tournés vers vous.

Connexions DHT11 et DHT22 à 4 broches

DHT11 / DHT22Arduino
Broche 15 V
Broche 2Connectez à la broche numérique 2 et à 5 V via une résistance de 10 kΩ
Broche 3Pas connecté
Broche 4GND

Vous pouvez également acheter les capteurs montés sur un petit PCB (capteurs à 3 broches). Ces cartes de dérivation facilitent la connexion du capteur à l’Arduino et incluent déjà une résistance de rappel. Assurez-vous de vérifier l’étiquette du capteur,  l’ordre des broches peut être différent selon le fabricant .

DHT11-3 broches-avec-Arduino-UNO-schéma-câblage-schématique
Câblage du capteur de température et d’humidité DHT11 à 3 broches à Arduino Uno

Connexions DHT11 à 3 broches

3 broches DHT11Arduino
sBroche numérique 2
+5 V
GND

Les exemples de code ci-dessous utilisent la broche numérique 2 pour recevoir les données du capteur, mais vous pouvez la remplacer par la broche numérique de votre choix.

DHT22-3 broches-avec-Arduino-UNO-schéma-câblage-schématique
Câblage du capteur de température et d’humidité DHT22 à 3 broches à Arduino Uno

Connexions DHT22 / AM2302 à 3 broches

3 broches DHT22Arduino
LEQUELBroche numérique 2
VCC5 V
GNDGND

Installation des bibliothèques Arduino requises

Le code ci-dessous utilise la  bibliothèque de capteurs Adafruit DHT  que vous pouvez télécharger  ici sur GitHub . Cette bibliothèque ne fonctionne que si vous avez également   installé la bibliothèque Adafruit Unified Sensor , qui est également  disponible sur GitHub .

Vous pouvez également télécharger les deux bibliothèques en cliquant sur les boutons ci-dessous:

Vous pouvez installer la bibliothèque en allant dans  Sketch> Inclure la bibliothèque> Ajouter une bibliothèque .ZIP  dans l’IDE Arduino.

Une autre option consiste à naviguer vers  Outils> Gérer les bibliothèques…  ou tapez Ctrl + Maj + I sous Windows. Le gestionnaire de bibliothèque ouvrira et mettra à jour la liste des bibliothèques installées.

Installation d'une bibliothèque Arduino Étape 1 Ouvrez Library Manager

Vous pouvez rechercher  «dht»  et  «adafruit unified sensor»  et rechercher la bibliothèque d’Adafruit. Sélectionnez la dernière version, puis cliquez sur Installer.

Installation d'une bibliothèque Arduino étape 2 DHT Adafruit

DHT11/DHT22 temperature and humidity sensor Arduino example code

You can upload the following example code to your Arduino using the Arduino IDE. Next, I will explain how the code works.

You can copy the code by clicking on the button in the top right corner of the code field.

/* Arduino example code for DHT11, DHT22/AM2302 and DHT21/AM2301 temperature and humidity sensors. More info: www.www.makerguides.com */
// Include the libraries:
#include <Adafruit_Sensor.h>
#include <DHT.h>
// Set DHT pin:
#define DHTPIN 2
// Set DHT type, uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
// Initialize DHT sensor for normal 16mhz Arduino:
DHT dht = DHT(DHTPIN, DHTTYPE);
void setup() {
  // Begin serial communication at a baud rate of 9600:
  Serial.begin(9600);
  // Setup sensor:
  dht.begin();
}
void loop() {
  // Wait a few seconds between measurements:
  delay(2000);
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read the humidity in %:
  float h = dht.readHumidity();
  // Read the temperature as Celsius:
  float t = dht.readTemperature();
  // Read the temperature as Fahrenheit:
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again):
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  // Compute heat index in Fahrenheit (default):
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius:
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" % ");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" \xC2\xB0");
  Serial.print("C | ");
  Serial.print(f);
  Serial.print(" \xC2\xB0");
  Serial.print("F ");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" \xC2\xB0");
  Serial.print("C | ");
  Serial.print(hif);
  Serial.print(" \xC2\xB0");
  Serial.println("F");
}

You should see the following output in the serial monitor (Ctrl + Shift + M):

DHT11 temperature and humidity sensor Serial Monitor output
Serial monitor output

Code explanation

The first step is to include the Adafruit DHT and Unified Sensor library.

// Include the libraries:
#include <Adafruit_Sensor.h>
#include <DHT.h>

Next, we need to define the DHT to Arduino connection pin and also set the DHT sensor type. In our example, we are using a DHT11 sensor connected to pin 2.

The statement #define is used to give a name to a constant value. The compiler will replace any references to this constant with the defined value when the program is compiled. So everywhere you mention DHTPIN, the compiler will replace it with the value 2 when the program is compiled.

// Set DHT pin:
#define DHTPIN 2
// Set DHT type, uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

Next, you need to create a new instance of the DHT class with the appropriate DHT type and connection. For this, we use the function DHT(pin,type).

In this case, I called the sensor ‘dht’ but you can use other names as well, like ‘temperature_sensor’ or ‘dht11’ etc. DHT temperature_sensor = DHT(DHTPIN, DHTTYPE);. You can create multiple instances of the DHT class with different names and pins/types. This allows you to easily use 2 or more sensors at the same time.

// Initialize DHT sensor for normal 16mhz Arduino:
DHT dht = DHT(DHTPIN, DHTTYPE);

In the setup(), we start serial communication at a baud rate of 9600. Make sure that the Serial Monitor is also set to 9600! We also initialize the sensor with dht.begin().

void setup() {
  // Begin serial communication at a baud rate of 9600:
  Serial.begin(9600);
  // Setup sensor:
  dht.begin();
}

The loop() section of the code starts with a delay of 2 seconds. This delay is there to give the sensor some time to do the readings. The maximum sensing rate of the DHT22 is every 2 seconds and that of the DHT11 is once every second.

// Wait a few seconds between measurements:
delay(2000);

Taking temperature and humidity readings is super easy because the library has several functions built-in. To get a humidity reading in ‘%’, you can use the function readHumidity(). In this case, we are saving the reading as the ‘h’ variable. Note that it is of the type float.

When you want to use a function on the DHT object, you first need to specify the name that you gave to the sensor. So in our case this is ‘dht’.

// Read the humidity in %:
float h = dht.readHumidity();

Taking temperature readings is just as easy with the function readTemperature().

// Read the temperature as Celsius:
float t = dht.readTemperature();

If you want to get the temperature in Fahrenheit instead of Celsius, you have two options. You can pass true to the readTemperature function, or you can use the convert function:

// Read the temperature as Fahrenheit:
float f = dht.readTemperature(true);
// Alternative, use convert function:
float f = dht.convertCtoF(t);

Next, there is a small section of code that checks if the sensor is connected correctly and is returning a reading. If not, an error message will be printed on the Serial Monitor.

// Check if any reads failed and exit early (to try again):
if (isnan(h) || isnan(t) || isnan(f)) {
  Serial.println("Failed to read from DHT sensor!");
  return;
}

The library also has a function built-in that can compute the heat index by combining the temperature and humidity readings. The heat index is also known as the “felt air temperature” or “apparent temperature”.

// Compute heat index in Fahrenheit (default):
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius:
float hic = dht.computeHeatIndex(t, h, false);

Finally, the readings are displayed on the Serial Monitor. Note that the line Serial.print(" \xC2\xB0"); is used to print the degree symbol.

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" % ");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" \xC2\xB0");
Serial.print("C | ");
Serial.print(f);
Serial.print(" \xC2\xB0");
Serial.print("F ");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" \xC2\xB0");
Serial.print("C | ");
Serial.print(hif);
Serial.print(" \xC2\xB0");
Serial.println("F");

Example code for DHT11 and DHT22/AM2302 temperature and humidity sensor with I2C LCD and Arduino

By combining a temperature and humidity sensor with a small LCD, you can create a cheap weather station.

In the following example, I will be using an I2C character LCD like this one from Amazon. You can read more about using an I2C LCD with Arduino in the article below:

If you have a normal LCD without an I2C backpack, check out the tutorial below:

You will need to make some extra connections to the Arduino so we can control the 16×2 character LCD. The DHT11 or DHT22/AM2302 sensor is connected in the same way as before.

The wiring diagram below shows you how to connect an I2C LCD to the Arduino.

DHT11-with-I2C-LCD-and-Arduino-UNO-wiring-diagram-schematic
DHT11 temperature and humidity sensor with 16×2 I2C character LCD and Arduino wiring diagram

The connections are also given in the following table:

I2C LCD Connections

I2C LCDArduino
GNDGND
VCC5 V
SDAA4
SCLA5

If you are not using an Arduino Uno, the SDA and SCL pins can be at a different location. An Arduino UNO with the R3 layout (1.0 pinout), also has the SDA (data line) and SCL (clock line) pin headers close to the AREF pin. Check the table below for more details.

BoardSDASCL
Arduino UnoA4A5
Arduino NanoA4A5
Arduino Micro23
Arduino Mega 25602021
Arduino Leonardo23
Arduino Due2021
I2C pin locations for different Arduino boards

The code uses the LiquidCrystal_I2C library, which you can download here on GitHub. It also includes the Wire.h library, which allows you to communicate with I2C devices. This library should come pre-installed with the Arduino IDE.

The code below is mostly the same as before, but now we display the temperature and humidity on the LCD instead of the Serial Monitor.

You can copy the code by clicking on the button in the top right corner of the code field.

/* Arduino example code for DHT11, DHT22/AM2302 and DHT21/AM2301 temperature and humidity sensors with I2C LCD. More info: www.www.makerguides.com */
// Include the libraries:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set DHT pin:
#define DHTPIN 2
// Define SDA and SCL pin for LCD:
#define SDAPin A4 // Data pin
#define SCLPin A5 // Clock pin
// Set DHT type, uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
// Initialize DHT sensor for normal 16mhz Arduino:
DHT dht = DHT(DHTPIN, DHTTYPE);
// Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered):
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2); //Change to (0x27,20,4) for 2004 LCD
void setup() {
  // Setup sensor:
  dht.begin();
  // Initiate the LCD:
  lcd.init();
  lcd.backlight();
}
void loop() {
  // Wait a few seconds between measurements:
  delay(2000);
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  // Read the humidity in %:
  float h = dht.readHumidity();
  // Read the temperature as Celsius:
  float t = dht.readTemperature();
  // Read the temperature as Fahrenheit:
  float f = dht.readTemperature(true);
  // Compute heat index in Fahrenheit (default):
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius:
  float hic = dht.computeHeatIndex(t, h, false);

  // Print the temperature and the humidity on the LCD:
  lcd.setCursor(0, 0);
  lcd.print("Temp: ");
  lcd.print(t);
  lcd.print(" " "\xDF" "C");
  lcd.setCursor(0, 1);
  lcd.print("Humid: ");
  lcd.print(h);
  lcd.print(" %");
}

You should see the following output on the LCD:

(Coming soon)


DHT11/DHT22 troubleshooting guide

When working with these sensors, you might get the following error messages:

“Failed to read from DHT sensor!”

This message can appear in the serial monitor when the sensor does not return a reading. This can have several causes:

  • Sensor type: Make sure you have uncommented the correct DHTTYPE in the code setup. Check the example above.
  • Sampling rate: The DHT sensors are quite slow, the maximum sampling rate is around 2 seconds. Increasing the delay between measurements might solve this error.
  • Power: Although the DHTxx sensors can work from 3.3 to 5 V, the manufacturer recommends 5 V. In some cases, powering the sensor with 5 V solves the problem. Make sure that your microcontroller also supports 5 V on the GPIO pins.

Fatal error: Adafruit_Sensor.h: No such file or directory

You might get this error when you try to compile the code. This means that you did not (properly) install the Adafruit Unified Sensor library.

Just scroll up a bit in this post and you will see where and how you can download and install the library.

Conclusion

In this article, I have shown you how DHT11 and DHT22/AM2302 temperature and humidity sensors work and how you can use them with Arduino. I hope you found it useful and informative. If you did, please share it with a friend who also likes electronics and making things!

I would love to know what projects you plan on building (or have already built) with this sensor. If you have any questions, suggestions or if you think that things are missing in this tutorial, please leave a comment down below.

Note that comments are held for moderation to prevent spam.

Creative Commons License

    Laisser un commentaire

    Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

    Rejoindre la liste d'attente Nous vous informerons lorsque le produit arrivera en stock. Veuillez laisser votre adresse E-mail et la quantité voulue.

    Main Menu

    بحاجة الى مساعدة ؟