BLOG / TUTORIALS / DHT22 Temperature and Humidity Sensor: C…
Статья блога

DHT22 Temperature and Humidity Sensor: Complete Arduino Tutorial

Viktor Build ~6 min read

Learn how to wire, code, and log data from the DHT22 temperature and humidity sensor with Arduino. Complete beginner guide with library setup and troubleshooting.

DHT22 Temperature and Humidity Sensor: Complete Arduino Tutorial

If you want to measure temperature and humidity with your Arduino, the DHT22 temperature sensor is the go-to choice for reliable, accurate readings without breaking the bank. In this complete beginner’s guide, I’ll show you exactly how to wire it up, install the right library, write clean code, and even log data over time. By the end, you’ll have a fully working environmental monitor that’s ready to be extended into weather stations, greenhouses, or home automation projects.

What Makes the DHT22 Temperature Sensor Better Than the DHT11?

Before we dive into wiring, let’s clear up the most common question: why the DHT22 over the cheaper DHT11?

The DHT22 is the upgraded sibling. Here’s the spec comparison:

Feature DHT22 DHT11
Temperature range -40°C to +80°C 0°C to +50°C
Accuracy ±0.5°C ±2°C
Humidity range 0–100% RH 20–80% RH
Humidity accuracy ±2% RH ±5% RH
Sampling rate 0.5 Hz (every 2 s) 1 Hz (every 1 s)
Price ~$3–5 ~$1–2

For most real-world projects, the DHT22’s wider range and better accuracy make it worth the extra two bucks. You can use it outdoors in winter, inside a reptile enclosure, or in a server closet without worrying about the readings going haywire.

What You’ll Need for This Tutorial

Grab these parts before we start:

  • Arduino board (Uno, Nano, Mega — any will work)
  • DHT22 sensor module (the 4-pin PCB version with a built-in pull-up resistor is easiest)
  • Breadboard
  • Jumper wires (male-to-female)
  • 10 kΩ resistor (only needed if you have the bare 4-pin DHT22 without a module)
  • USB cable for power and programming
  • Computer with Arduino IDE installed

If you’re using the sensor module (the one with three pins and a small PCB), you don’t need the extra resistor — it’s already on board.

Wiring the DHT22 Temperature Sensor to Arduino

The DHT22 has four pins (or three on the module version). Here’s how to connect them:

Pinout for the bare DHT22 (4 pins, left to right with the flat face toward you):

  1. VCC (pin 1) — 3.3V or 5V
  2. DATA (pin 2) — any digital pin (we’ll use pin 2)
  3. NC (pin 3) — not connected
  4. GND (pin 4) — ground

Wiring diagram:

DHT22 Pin Arduino Pin
VCC (pin 1) 5V
DATA (pin 2) Digital pin 2
NC (pin 3) (leave unconnected)
GND (pin 4) GND

If you’re using the bare DHT22 (not the module), add a 10 kΩ pull-up resistor between the DATA pin and VCC (5V). This is critical — without it, the communication will fail intermittently.

If you’re using the DHT22 module (usually labeled with three pins: VCC, DATA, GND), just connect VCC→5V, DATA→pin 2, GND→GND. The pull-up resistor is pre-soldered.

Installing the DHT Sensor Library

Arduino doesn’t know how to talk to the DHT22 natively. You need the DHT sensor library by Adafruit plus the Adafruit Unified Sensor library.

Step-by-step library install:

  1. Open the Arduino IDE
  2. Go to Tools → Manage Libraries (or press Ctrl+Shift+I)
  3. In the search box, type DHT sensor library
  4. Find the one by Adafruit — click Install
  5. When prompted, click Install All to include the Adafruit Unified Sensor dependency

That’s it. Now Arduino can decode the funky single-wire protocol the DHT22 uses.

Arduino Code: Read Temperature and Humidity

Here’s the simplest working sketch. Upload it and open the Serial Monitor (set baud rate to 9600).

#include <DHT.h>

#define DHTPIN 2          // Digital pin connected to the DHT22
#define DHTTYPE DHT22     // DHT 22 (AM2302), AM2321

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHT22 test!"));
  dht.begin();
}

void loop() {
  // Wait 2 seconds between measurements (DHT22 max rate)
  delay(2000);

  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();       // Celsius
  float tempFahrenheit = dht.readTemperature(true); // Fahrenheit

  // Check if any reads failed
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F("%  Temperature: "));
  Serial.print(temperature);
  Serial.print(F("°C "));
  Serial.print(tempFahrenheit);
  Serial.println(F("°F"));
}

What this code does:

  • #define DHTTYPE DHT22 tells the library which sensor you’re using
  • dht.begin() initializes communication
  • dht.readTemperature() returns °C, pass true for °F
  • dht.readHumidity() returns relative humidity as a percentage
  • The isnan() check catches read failures (loose wiring, bad sensor, or timing issues)

You should see output like this every 2 seconds:

Humidity: 45.60%  Temperature: 22.30°C 72.14°F

Adding Data Logging with Timestamps

Reading values is nice, but logging them with timestamps is where things get useful. Here’s an improved version that prints a CSV-friendly line you can copy-paste into a spreadsheet or save to a file.

#include <DHT.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
  Serial.println(F("Timestamp,Humidity(%),Temp(C),Temp(F)"));
}

void loop() {
  delay(2000);

  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();
  float tempFahrenheit = dht.readTemperature(true);

  if (isnan(humidity) || isnan(temperature)) {
    Serial.println(F("ERROR, read failed"));
    return;
  }

  unsigned long now = millis();
  Serial.print(now);
  Serial.print(F(","));
  Serial.print(humidity, 1);
  Serial.print(F(","));
  Serial.print(temperature, 1);
  Serial.print(F(","));
  Serial.println(tempFahrenheit, 1);
}

The output is now:

0,45.6,22.3,72.1
2000,45.5,22.3,72.1
4000,45.4,22.4,72.3

Copy the serial output, paste it into a text file, save as .csv, and open it in Excel or Google Sheets. You’ll instantly get a graph of your room’s environmental changes.

Common Problems and How to Fix Them

The DHT22 temperature sensor is robust, but beginners often hit these issues:

1. “Failed to read from DHT sensor!” or NaN readings

  • Check wiring — especially the DATA pin connection
  • Missing pull-up resistor — without a 10kΩ resistor between DATA and VCC, the signal won’t be stable
  • Wrong pin number — double-check #define DHTPIN matches your wiring
  • Bad sensor — some cheap clones are DOA. Swap it out if nothing works

2. Values that never change

  • The DHT22 updates every 2 seconds maximum. If you call read() faster than that, it returns the previous reading. That’s normal.
  • If it’s stuck on 0.0 or 100%, your sensor might be dead

3. Jittery readings

  • Long wires can act as antennas. Keep the DATA wire shorter than 20 cm
  • Add a 100 nF capacitor between VCC and GND near the sensor to smooth power noise

4. Temperature reads 1–2°C too high

  • The DHT22 self-heats slightly. Don’t hold it in your hand for too long
  • Keep it away from the Arduino’s voltage regulator, which gets warm

Next Steps: What to Build with the DHT22

Once you have the basic reading working, the possibilities open up:

  • Add an OLED Display Arduino to show temperature and humidity without a computer
  • Log data to an SD card for long-term environmental monitoring
  • Trigger a relay or fan when temperature exceeds a threshold — similar to my Remote Control Fan with ESP8266 project
  • Send data to the cloud with an ESP8266 or ESP32 for remote monitoring
  • Combine with a potentiometer to set a temperature threshold manually

The DHT22 is one of those sensors that looks simple but becomes the heart of countless projects once you start experimenting.

Why the DHT22 Temperature Sensor Belongs in Every Beginner’s Toolkit

The DHT22 strikes a perfect balance: accurate enough for climate monitoring, cheap enough to buy five at once, and simple enough to code in ten minutes. It’s not the fastest sensor, but for 99% of hobbyist projects — weather stations, terrariums, server temperature monitors, or smart greenhouse controllers — it’s exactly what you need.

Grab a sensor, wire it up, and run the code above. Within five minutes you’ll be watching your room’s temperature and humidity live on the Serial Monitor. From there, the only limit is what you decide to build with the data.

Присоединяйся к сообществу в Discord

Задавай вопросы, делись своими сборками и общайся с другими мейкерами.

Присоединиться к Discord — бесплатно

Понравился туториал?

Поддержи канал на Patreon и получи ранний доступ к проектам и многому другому.

Поддержать на Patreon →