dht22.ino

ESP32-S2 · File : dht22.ino · Language : Arduino · Use case : Lire température et humidité avec un DHT22

The DHT22 delivers temperature and humidity over a single wire: the Adafruit library decodes the 40-bit frames and the sketch adds the dew point. The 2 s cadence is the sensor's hard limit.

Hardware required

An ESP32-S2 board (single-core Xtensa, Wi-Fi, native USB-OTG on GPIO19/20, 14 capacitive touch pads) such as a DevKitC-1 or QT Py, powered over USB. 1 DHT22 (3-pin module with built-in pull-up) or bare DHT22 + 10 kΩ.

Wiring

VDD 3.3 V, DATA on GPIO4 with 10 kΩ pull-up to 3.3 V, GND. The DHT11 also works (change DHTTYPE).

How it works

readTemperature/readHumidity run a full acquisition (start bit + 40 timed bits). The sensor is slow, so loop passes are skipped until 2 s; NaNs flag a lost frame. In the Arduino IDE (esp32 package), select « ESP32S2 Dev Module »; the S2 flashes straight over its native USB (double reset on some boards to enter the bootloader).

Going further

Show on the OLED of the next sketch, or publish readings over BLE/Wi-Fi to a dashboard.

dht22.ino

// DHT22 sur GPIO4 — bibliothèque « DHT sensor library » (Adafruit).
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
unsigned long precedent = 0;

void setup() {
  Serial.begin(115200);
  dht.begin();
  Serial.println("DHT22 pret (2 s entre mesures)");
}

void loop() {
  if (millis() - precedent < 2000) return;   // le DHT22 parle au mieux à 0,5 Hz
  precedent = millis();

  float t = dht.readTemperature();
  float h = dht.readHumidity();
  if (isnan(t) || isnan(h)) {
    Serial.println("Echec de lecture : cabling/alimentation ?");
    return;
  }
  float dew = 243.04 * (17.625 * t / (t + 243.04) + log(h / 100.0))
            / (17.625 - (17.625 * t / (t + 243.04) + log(h / 100.0)));
  Serial.printf("T=%.1f C  HR=%.1f %%  point de rosee=%.1f C\n", t, h, dew);
}

← Back to the board