portfolio

DHT22 Code

Course Content
Session 1: Introduction to ESP32
Objective: Get familiar with the ESP32 microcontroller and set up the development environment.
0/5
Session 2: Interfacing with Sensors and Displays
Learn how to connect a DHT22 sensor and an OLED display to the ESP32.
0/4
Session 4: Programming the OLED Display
Objective: Write code to display information on the OLED display.
0/4
Session 5: Integrating Sensor Data with OLED Display
Objective: Combine sensor readings with OLED display functionality.
0/1
Session 6: Setup WIFI Capability
0/1
Session 7: Adding a Webserver
0/1
Session 8: Wrap-up
0/1
ESP32 Basics
About Lesson

To interface the DHT22 sensor with the ESP32 using the Arduino IDE, you can use the DHT sensor library by Adafruit. Below is a detailed guide and the complete code.

Step-by-Step Guide:

  1. Install the Required Libraries:

    • Open the Arduino IDE.
    • Go to Sketch > Include Library > Manage Libraries...
    • Search for and install DHT sensor library by Adafruit and Adafruit Unified Sensor

ESP32 with DHT22 Code:

C++
#include "DHT.h"

// Set the GPIO pin for the DHT22 sensor
#define DHTPIN 4      // GPIO pin where the DATA pin of the DHT22 is connected

// Set the DHT sensor type
#define DHTTYPE DHT22

// Initialize the DHT sensor
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  // Start the serial communication
  Serial.begin(115200);
  
  // Start the DHT sensor
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements
  delay(2000);

  // Read humidity and temperature from the sensor
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature(); // Celsius
  
  // Check if any reading failed
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Print the values to the Serial Monitor
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" *C");
}
  

Key Code Details:

  • DHTPIN: This defines the ESP32 GPIO pin connected to the DATA pin of the DHT22. Change this to whatever pin you’re using.
  • DHTTYPE: Defines the type of DHT sensor you’re using (DHT22 in this case).
  • dht.begin(): Initializes the DHT sensor.
  • dht.readHumidity(): Reads the humidity value from the sensor.
  • dht.readTemperature(): Reads the temperature value in Celsius.

Serial Monitor Output Example:

YAML
Humidity: 55.20 %  Temperature: 23.40 *C
Humidity: 55.30 %  Temperature: 23.45 *C

Notes:

  • The delay(2000) ensures a 2-second pause between readings, as the DHT22 takes around 2 seconds to complete a reading.
  • If the readings return NAN (not a number), there could be a wiring issue, or the sensor might be faulty.

With this setup, you should be able to read temperature and humidity from the DHT22 sensor using the ESP32 and Arduino IDE.