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.
Core Component: The DHT22 Sensor
Section titled “Core Component: The DHT22 Sensor”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.
Key Specifications
Section titled “Key Specifications”- 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)
Required Components
Section titled “Required Components”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
Circuit and Wiring
Section titled “Circuit and Wiring”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.
Setting up the Software
Section titled “Setting up the Software”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.
- Open the Arduino IDE (version 2.0+ is recommended).
- Navigate to Tools > Manage Libraries… or click the Library Manager icon on the left.
- In the search bar, type
DHT sensor library. - Find the library by Adafruit and click Install. The IDE may ask to install dependencies like
Adafruit Unified Sensor. Click Install All.
Arduino Sketch
Section titled “Arduino Sketch”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 toconst int DHT_PIN = 2;
// --- Global Objects ---// Initialize the DHT sensor objectDHT 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"));}Code Explanation
Section titled “Code Explanation”#includedirectives: These load the necessary libraries for the DHT sensor and the underlying Adafruit sensor framework.#defineandconst 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();: Insetup(), this initializes communication with the sensor.dht.readHumidity()&dht.readTemperature(): Inloop(), 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.
Viewing the Results
Section titled “Viewing the Results”- Upload the code to your Arduino board.
- Open the Serial Monitor (Tools > Serial Monitor or Ctrl+Shift+M).
- Make sure the baud rate is set to 9600.
- You should see the humidity and temperature readings updated every two seconds.
Debugging Common Issues
Section titled “Debugging Common Issues”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 correctDHT_PINin your code.- Readings are
nanor0: 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.
Next Steps & Project Ideas
Section titled “Next Steps & Project Ideas”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.