DHT sensor library
Adafruit Unified Sensor

1.Develop an ESP32 program to read temperature and humidity values using a DHT22 sensor and display the readings using serial communication.

sketch.ino:

#include "DHT.h"

#define DHTPIN 4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

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

  dht.begin();

  Serial.println("DHT22 Sensor Started");
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT22 sensor!");
    delay(2000);
    return;
  }

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" °C");

  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.println(" %");

  Serial.println("--------------------");

  delay(2000);
}

diagram.json:


{
  "version": 1,
  "author": "Tony",
  "editor": "wokwi",
  "parts": [
    {
      "type": "board-esp32-devkit-c-v4",
      "id": "esp",
      "top": 0,
      "left": 0,
      "attrs": {}
    },
    {
      "type": "wokwi-dht22",
      "id": "dht",
      "top": -20,
      "left": 200,
      "attrs": {}
    }
  ],
  "connections": [
    ["esp:TX", "$serialMonitor:RX", "", []],
    ["esp:RX", "$serialMonitor:TX", "", []],
    ["dht:VCC", "esp:3V3", "red", []],
    ["dht:GND", "esp:GND.1", "black", []],
    ["dht:SDA", "esp:4", "green", []]
  ],
  "dependencies": {}
}
