Build an Arduino temperature and humidity logger with DHT22

Sharing is caring!

Build an Arduino Temperature and Humidity Logger with DHT22

Free daily electronics newsletter — tutorials, news, and tips delivered daily.

Subscription Form

Ever wonder why your 3D prints fail on humid days, or why your bedroom feels stuffy at 3 AM? The answer is floating invisibly in the air around you — and with a $5 sensor and an Arduino, you can track it 24/7. In this tutorial, you’ll build a complete temperature and humidity data logger that records environmental conditions over time, perfect for monitoring your workspace, greenhouse, or even your pet’s habitat.

Difficulty: Beginner

Arduino Uno board with sensor on breadboard
Photo by Vishnu Mohanan on Unsplash

By the end of this project, you’ll have a working system that measures temperature and humidity every few seconds, stores the data, and displays real-time readings. Plus, you’ll learn fundamental Arduino concepts like sensor interfacing, data logging, and Serial communication — skills that transfer to countless other electronics projects.

Why the DHT22 Sensor?

The DHT22 (also called AM2302) is the Swiss Army knife of hobbyist environmental sensors. It measures both temperature and relative humidity with decent accuracy: ±0.5°C for temperature and ±2% for humidity. Unlike its cheaper cousin the DHT11, the DHT22 handles a wider range (-40°C to 80°C) and provides better precision.

What makes it beginner-friendly? Simple single-wire digital communication. No analog voltage conversions, no complex calibration — just plug it in, load a library, and you’re reading data. It’s the sensor I recommend to anyone taking their first steps beyond blinking LEDs. If you’re just getting comfortable with the basics of electronic components, the DHT22 is your perfect next challenge.

What You’ll Need

This project requires minimal components — you probably have most of them in your starter kit already:

Optional but recommended: an SD card module if you want to log data without keeping your computer connected. For this tutorial, we’ll start with the simpler Serial Monitor approach — you can always add SD card logging later as an upgrade.

Understanding the DHT22 Pinout

DHT22 AM2302 pinout diagram showing VCC, DATA, NC, and GND pins
DHT22 pinout diagram — Pin 1: VCC, Pin 2: DATA, Pin 3: NC, Pin 4: GND (view full datasheet)

The DHT22 has four pins, but you’ll only use three of them:

  • Pin 1 (VCC): Power supply, connect to Arduino 5V
  • Pin 2 (DATA): Digital signal pin, connects to a digital pin on Arduino
  • Pin 3: Not connected (leave it floating)
  • Pin 4 (GND): Ground, connect to Arduino GND

Here’s the catch that trips up beginners: the DATA pin needs a pull-up resistor. Think of it as holding the line “high” by default so the sensor can pull it low to send signals. Without this 10kΩ resistor between VCC and DATA, you’ll get erratic readings or no data at all.

Some DHT22 modules come mounted on breakout boards with the pull-up resistor already soldered on. If yours has only three pins labeled VCC, DATA, and GND, congratulations — the resistor is built in. If it has four pins like the raw sensor, you’ll need to add the resistor yourself.

Arduino wired to sensors on a breadboard
Photo by Vishnu Mohanan on Unsplash

Wiring the Circuit

Let’s connect everything step by step. With your Arduino unplugged from USB (always wire circuits with power off), follow these connections:

  1. Insert the DHT22 into your breadboard with each pin in a different row
  2. Connect DHT22 Pin 1 (VCC) to Arduino 5V using a jumper wire
  3. Connect DHT22 Pin 2 (DATA) to Arduino digital pin 2
  4. Place the 10kΩ resistor between the breadboard rows connected to VCC and DATA (if your sensor doesn’t have a built-in resistor)
  5. Connect DHT22 Pin 4 (GND) to Arduino GND

Double-check your connections before plugging in. The most common mistake? Connecting the sensor backwards. The DHT22 usually has a small “+” symbol near Pin 1 — make sure that’s going to 5V, not ground.

This simple circuit demonstrates one of the beautiful things about modern sensors: minimal external components needed. Compare this to older analog sensors that required amplifier circuits, voltage dividers, and careful calibration. The DHT22 does all the hard work internally.

Installing the DHT Library

Before we write code, we need to install the DHT sensor library. This library handles all the timing-critical communication with the sensor so you don’t have to.

Open the Arduino IDE and follow these steps:

  1. Click Sketch → Include Library → Manage Libraries
  2. In the Library Manager search box, type “DHT sensor library”
  3. Find “DHT sensor library by Adafruit” and click Install
  4. When prompted, install all dependencies (it will ask to install the “Adafruit Unified Sensor” library too)
  5. Close the Library Manager

Libraries are one of Arduino’s superpowers. Instead of writing hundreds of lines of code to handle sensor timing, someone else (in this case, the excellent team at Adafruit) has done it for you. Standing on the shoulders of giants, as they say.

Code in an editor
Photo by Patrick Martin on Unsplash

Writing the Code

Now for the fun part. Copy this code into a new Arduino sketch:

#include "DHT.h"

// Define the pin and sensor type
#define DHTPIN 2        // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT22 (AM2302)

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

void setup() {
  // Start serial communication
  Serial.begin(9600);
  Serial.println("Temperature and Humidity Logger");
  Serial.println("-------------------------------");
  
  // Initialize sensor
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements
  delay(2000);
  
  // Read humidity
  float humidity = dht.readHumidity();
  
  // Read temperature in Celsius
  float tempC = dht.readTemperature();
  
  // Read temperature in Fahrenheit
  float tempF = dht.readTemperature(true);
  
  // Check if any reads failed
  if (isnan(humidity) || isnan(tempC) || isnan(tempF)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  // Calculate heat index in Fahrenheit
  float heatIndexF = dht.computeHeatIndex(tempF, humidity);
  
  // Calculate heat index in Celsius
  float heatIndexC = dht.computeHeatIndex(tempC, humidity, false);
  
  // Print results to Serial Monitor
  Serial.print("Humidity: ");
  Serial.print(humidity);
  Serial.print("%  |  Temperature: ");
  Serial.print(tempC);
  Serial.print("°C / ");
  Serial.print(tempF);
  Serial.print("°F  |  Heat Index: ");
  Serial.print(heatIndexC);
  Serial.print("°C / ");
  Serial.print(heatIndexF);
  Serial.println("°F");
}

Let’s break down what this code does:

The #include statement loads the DHT library. The #define lines tell the program which pin you’re using and which sensor type you have. In setup(), we start Serial communication at 9600 baud (the speed at which data flows to your computer) and initialize the sensor.

The loop() function runs continuously. Every 2 seconds (the delay(2000)), it reads humidity and temperature, checks if the readings are valid (the isnan() check catches sensor errors), calculates heat index (how hot it actually feels considering humidity), and prints everything to the Serial Monitor.

Heat index is a bonus feature that’s surprisingly useful. On a humid summer day, 30°C might feel like 35°C because sweat doesn’t evaporate efficiently. The DHT library calculates this for you.

Uploading and Testing

Connect your Arduino to your computer via USB. In the Arduino IDE:

  1. Select your board type: Tools → Board → Arduino Uno (or your specific board)
  2. Select your port: Tools → Port → (choose the port with your Arduino connected)
  3. Click the Upload button (right arrow icon)

After uploading completes, open the Serial Monitor by clicking the magnifying glass icon in the top right, or press Ctrl+Shift+M. Make sure the baud rate dropdown in the bottom right is set to 9600.

You should see temperature and humidity readings appearing every two seconds. Try breathing on the sensor — humidity will spike. Cup your hands around it — temperature will rise. This immediate feedback is incredibly satisfying, and it’s how you know everything works.

If you see “Failed to read from DHT sensor!” repeatedly, check three things: Is the sensor connected to pin 2? Is the pull-up resistor installed correctly? Is the sensor getting power?

Digital temperature and humidity display
Photo by Kaffeebart on Unsplash

Interpreting Your Data

Now that you have data flowing, what does it mean? Room temperature typically ranges from 18°C to 24°C (64°F to 75°F). Comfortable humidity for humans is 30% to 60%. Below 30% and you get dry skin and static shocks. Above 60% and you risk mold growth and that clammy feeling.

You might notice readings fluctuate slightly — that’s normal. The DHT22 has ±2% accuracy, and environmental conditions genuinely change moment to moment. Air conditioning cycling on, a door opening, even someone walking past can affect readings.

Fun experiment: Boil water in a kettle near your sensor and watch humidity climb. Or open a window on a cold day and watch temperature drop. You’re seeing invisible environmental variables made visible through electronics — that’s the magic that hooked many of us into this hobby.

Upgrading Your Logger

This basic version logs data to your computer screen, but you can expand it in many directions:

Add an LCD display: Mount a 16×2 LCD to show readings without a computer. You’ll practice I2C communication and create a standalone device.

Log to SD card: Add an SD card module to store weeks of data. You can then import it into Excel or Python for analysis. This teaches you file handling and data persistence.

Add wireless transmission: Install an ESP8266 WiFi module to upload data to the cloud. You could monitor your workshop from your phone anywhere in the world.

Build an environmental control system: Add relays to control a fan when temperature exceeds a threshold, or a humidifier when humidity drops too low. Suddenly you’ve built a thermostat.

Each upgrade builds on the foundation you’ve created today. That’s the beauty of modular electronics — projects grow with your skills. Many successful projects started exactly like this: a simple sensor, then one improvement, then another, until suddenly you’ve built something remarkable.

Troubleshooting Common Issues

Problem: Serial Monitor shows nothing.
Solution: Check that you selected the correct port in Tools → Port. Also verify your baud rate is 9600.

Problem: Readings show NaN or all zeros.
Solution: The sensor isn’t communicating. Verify the DATA pin connection and ensure your pull-up resistor is installed correctly. Try connecting DATA to a different digital pin and updating the code.

Problem: Temperature seems accurate but humidity shows 99.9% constantly.
Solution: Your sensor might be damaged by moisture exposure. DHT22 sensors can fail if condensation forms inside. Try gently warming it with a hair dryer on low setting.

Problem: Readings fluctuate wildly.
Solution: This often indicates a loose connection. Press down firmly on all jumper wire connections. Breadboards can develop intermittent contacts over time.

Remember, troubleshooting is where real learning happens. Understanding the hazards of electricity and debugging circuits builds intuition that serves you in every future project.

Real-World Applications

Temperature and humidity logging isn’t just a learning exercise — it solves real problems. Here are projects I’ve seen hobbyists build:

  • Reptile habitat monitoring: Ensuring proper conditions for pet snakes and lizards
  • Cigar humidor control: Maintaining the precise 70% humidity cigars need
  • 3D printer enclosure: Monitoring temperature to prevent warping on large ABS prints
  • Home brewing: Tracking fermentation chamber conditions
  • Greenhouse automation: Triggering ventilation when it gets too hot or humid
  • Server room monitoring: Getting alerts before electronics overheat
  • Museum display cases: Protecting sensitive artifacts from humidity damage

Once you have reliable environmental data, you can make informed decisions instead of guessing. Is your bedroom actually too hot at night, or does it just feel that way? Log it for a week and you’ll know.

Conclusion

You’ve just built a working data logger that measures invisible environmental variables and makes them visible. More importantly, you’ve learned skills that transfer to countless other projects: working with sensors, debugging circuits, and handling real-time data.

The DHT22 is often the gateway sensor — the one that shows you how easy it can be to interface with the physical world. From here, you might explore temperature-based automation, weather stations, or any of the hundreds of other sensors available for Arduino.

Every expert started where you are right now: wiring up their first sensor, wondering if it would work, then seeing data appear on screen. That moment when invisible air properties become numbers you can read — that’s the spark that ignites a lifelong hobby.

Keep experimenting, keep building, and don’t be afraid to modify this project to suit your needs. The best projects solve problems you actually have, not just follow tutorials. What will you monitor first?

Want more electronics tutorials every day?

Join thousands of hobbyists — get free tutorials, news, and one component explained simply every day.

Subscription Form

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top