Skip to content

Arduino - Humidity Sensor

Arduino - Interfacing with a Humidity Sensor

Section titled “Arduino - Interfacing with a Humidity Sensor”

Modern electronics projects often need to sense their environment. In this tutorial, we’ll explore how to connect sensors to your Arduino. We’ll focus on the popular DHT22 sensor to measure both humidity and temperature, a common task in weather stations, home automation, and agricultural tech.

While this guide focuses on the DHT22, the principles apply to a wide range of digital sensors. We’ll also briefly discuss other popular sensors like the BME280 for more advanced projects.

The DHT22 (also sold as AM2302) is a versatile and low-cost digital sensor that measures relative humidity and temperature. It packages a capacitive humidity sensor and a thermistor into a single unit that communicates over a one-wire digital interface, making it easy to use with microcontrollers like the Arduino.

  • Power: 3.3V - 5V DC
  • Current: 2.5mA max during measurement
  • Humidity Range: 0-100% with 2-5% accuracy
  • Temperature Range: -40 to 80°C with ±0.5°C accuracy
  • Interface: Digital (1-Wire)

To build this project, you will need:

  • 1 × Arduino Uno R3 (or any other Arduino board)
  • 1 × Breadboard
  • 1 × DHT22 sensor
  • 1 × 10kΩ resistor (as a pull-up resistor)
  • Jumper wires

Connecting the DHT22 is straightforward. Follow these connections carefully. The pins on the DHT22 are typically numbered 1 to 4 from left to right when facing the grid-side of the sensor.

  • DHT22 Pin 1 (VCC) → Arduino 5V
  • DHT22 Pin 2 (Data) → Arduino Digital Pin 2
  • DHT22 Pin 3 (NC) → Not connected (leave empty)
  • DHT22 Pin 4 (GND) → Arduino GND

Crucial Step: A pull-up resistor is required for reliable communication. Connect the 10kΩ resistor between Pin 1 (VCC) and Pin 2 (Data) of the DHT22.

Before writing the code, you need to install a library to handle the complex communication protocol of the DHT sensor. We will use the popular DHT sensor library by Adafruit.

  1. Open the Arduino IDE (version 2.0+ is recommended).
  2. Navigate to Tools > Manage Libraries… or click the Library Manager icon on the left.
  3. In the search bar, type DHT sensor library.
  4. Find the library by Adafruit and click Install. The IDE may ask to install dependencies like Adafruit Unified Sensor. Click Install All.

Create a new sketch and paste the following code. This code initializes the sensor, reads the humidity and temperature every two seconds, and prints the values to the Serial Monitor.

/**
* @file dht22_modern_example.ino
* @author Your Name
* @brief A modern, clean example for reading temperature and humidity from a DHT22 sensor.
* @version 0.1
* @date 2023-10-27
*/
// Include the required libraries
#include <Adafruit_Sensor.h>
#include "DHT.h"
// --- Constants ---
// Define the type of DHT sensor we are using (DHT11, DHT21, DHT22)
#define DHTTYPE DHT22
// Define the digital pin the DHT sensor is connected to
const int DHT_PIN = 2;
// --- Global Objects ---
// Initialize the DHT sensor object
DHT dht(DHT_PIN, DHTTYPE);
void setup() {
// Start serial communication for debugging purposes
Serial.begin(9600);
Serial.println(F("\nDHT22 Sensor Test!"));
// Initialize the sensor
dht.begin();
}
void loop() {
// Wait a couple of seconds between measurements.
// The DHT22 sensor is slow and can only be read every 2 seconds.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor).
float humidity = dht.readHumidity();
// Read temperature as Celsius (the default)
float temperature_c = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
// isnan() checks if a value is "not a number", which indicates a read error.
if (isnan(humidity) || isnan(temperature_c)) {
Serial.println(F("Error: Failed to read from DHT sensor!"));
return; // Exit the loop() function and try again on the next iteration
}
// --- Data Processing and Output ---
// Optionally, convert temperature to Fahrenheit
float temperature_f = temperature_c * 1.8 + 32.0;
// Print the results to the Serial Monitor with clear labels and units.
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.println(F(" %"));
Serial.print(F("Temperature: "));
Serial.print(temperature_c);
Serial.print(F(" °C / "));
Serial.print(temperature_f);
Serial.println(F(" °F"));
}
  • #include directives: These load the necessary libraries for the DHT sensor and the underlying Adafruit sensor framework.
  • #define and const int: We use these to define our sensor type and pin number. Using constants makes the code easier to read and modify.
  • DHT dht(DHT_PIN, DHTTYPE);: This creates an instance of the DHT object, telling the library which pin to use and what kind of sensor it is.
  • dht.begin();: In setup(), this initializes communication with the sensor.
  • dht.readHumidity() & dht.readTemperature(): In loop(), these functions retrieve the latest data from the sensor.
  • Error Handling: The if (isnan(humidity) || ...) block is crucial. It checks if the sensor returned valid numbers. If not, it prints an error message and skips the rest of the loop, preventing your program from using bad data.
  1. Upload the code to your Arduino board.
  2. Open the Serial Monitor (Tools > Serial Monitor or Ctrl+Shift+M).
  3. Make sure the baud rate is set to 9600.
  4. You should see the humidity and temperature readings updated every two seconds.
  • Error: Failed to read from DHT sensor!: This is the most common problem. Double-check your wiring, especially VCC and GND. Ensure the 10kΩ pull-up resistor is correctly placed between the Data and VCC lines. Verify you’ve defined the correct DHT_PIN in your code.
  • Readings are nan or 0: This also points to a wiring or power issue. Some DHT sensors are sensitive; ensure your Arduino is providing a stable 5V.
  • Code Fails to Compile: Make sure you have installed the Adafruit DHT sensor library and its dependencies correctly.

Now that you can read environmental data, the possibilities are endless!

  • Mini-Project: Simple Thermostat: Add two LEDs (e.g., red and blue). Turn on the red LED if the temperature exceeds a certain threshold and the blue one if it falls below another.
  • Go IoT: Use an Arduino with Wi-Fi capabilities (like a Nano 33 IoT or an ESP32) to send this data to a cloud service like Arduino IoT Cloud or ThingSpeak to monitor your room from anywhere.
  • Upgrade Your Sensor: For higher accuracy and stability, consider using a BME280 sensor. It communicates over the I2C protocol and also measures barometric pressure.