Raspberry Pi Humidity Sensor using the DHT22?

The DHT22 is a low-cost digital humidity and temperature sensor that can be easily interfaced with a Raspberry Pi to measure and monitor environmental conditions. This guide will walk through the hardware setup, software configuration, and different options for recording sensor data such as broadcasting readings or logging to a file.

Raspberry Pi Humidity Sensor using the DHT22?

Hardware Setup

Interfacing the DHT22 with a Raspberry Pi is straightforward thanks to the single-bus data connections. Follow these steps for the physical hardware setup:

  • The DHT22 sensor has four pins – two for power and ground, one for data, and an unused pin.
  • Connect the VCC pin to Raspberry Pi 3.3V power.
  • Connect the GND pin to any Raspberry Pi ground pin.
  • Connect the DATA pin to Raspberry Pi GPIO 4 (pin 7). This can be changed later in software.
  • Lastly, connect a 10K pull-up resistor from the data line to 3.3V. This helps stabilize signal communication.

Once connected, the hardware is ready to start sensing humidity and temperature. Next configure the software to interact with the sensor.

Reading Sensor Data with Adafruit DHT Library

Adafruit provides an open-source Python library called Adafruit_DHT to abstract away low-level details for reading many DHT sensor types. This simplifies collecting data in just three lines of code:

import Adafruit_DHT

sensor = Adafruit_DHT.DHT22

humidity, temperature = Adafruit_DHT.read_retry(sensor, 4)

The sensor type and GPIO pin number are specified, then sensor readings are retrieved with one function call. Error handling has also been incorporated for unreliable connections. With the library set up, sensor data can now be handled in different ways.

Broadcasting Sensor Readings

For real-time monitoring, continuously read and broadcast sensor data. This allows collecting readings over time to assess environmental changes.

Use a loop to read the sensor and print readings. Broadcasting at 1 second intervals provides responsive sensor updates:

while True:

  humidity, temperature = Adafruit_DHT.read_retry(sensor, 4)

  print(“Temp: {:.1f} C    Humidity: {}% “.format(temperature, humidity))

  time.sleep(1)

The formatted print statement outputs the data clearly. This can be extended to trigger events based on threshold values too. While great for monitoring, all data is lost when the script stops. For data logging and storage, write readings to a file instead.

Logging Sensor Data to a File

Recording sensor data to a file allows long-term storage for further analysis. Append timestamped sensor readings by opening a file and writing on each reading:

file = open(“/home/pi/sensor_log.csv”, “a”)

while True:

  humidity, temperature = Adafruit_DHT.read_retry(sensor, 4)

  file.write(“{0}, {1:.1f}, {2}\n”.format(dt.datetime.now(), temperature, humidity))

  time.sleep(60)

file.close()

This efficiently logs CSV formatted data every minute, ready for importing and graphing in spreadsheet software. But writing to an SD card can cause corruption over long durations. For robust data logging, use a database instead.

Storing Sensor Data in a Database

A database provides reliable storage for sensor data and integrates well with web visualizations. Python module MySQL Connector connects to a MySQL server and handles inserting data.

Follow these steps to configure a database and save sensor readings:

  1. Create a MySQL database and table

— Create database

CREATE DATABASE sensor_log;

— Create table

CREATE TABLE dht22_data (

  id INT NOT NULL AUTO_INCREMENT,

  reading_time DATETIME,  

  temperature DECIMAL(5,2),

  humidity INT,

 PRIMARY KEY (id)

Install MySQL Connector module

pip install mysql-connector-python

Insert sensor readings into table

import mysql.connector

db = mysql.connector.connect(

  host=”localhost”,

  user=”user”,

  password=”********”,

  database=”sensor_log”

cursor = db.cursor()

while True:

  humidity, temperature = Adafruit_DHT.read_retry(sensor, 4)

  cursor.execute(“””INSERT INTO dht22_data (reading_time, temperature, humidity) 

              VALUES (now(), %s, %s)”””, (temperature, humidity))

  db.commit()

  1.   time.sleep(60)

This provides robust storage for long term sensor logging. The data can also be easily accessed from web dashboards for visualization.

Overall, the DHT22 Raspberry Pi integration allows flexible options for reading, displaying, recording, and storing humidity and temperature data. After setting up hardware and software, the sensor can be used in many Internet of Things and environmental monitoring projects further.

Key Takeaways

  • The DHT22 provides digital humidity and temperature readings when interfaced with a Raspberry Pi GPIO pin.
  • The Adafruit_DHT library simplifies reading sensor data in Python scripts.
  • Sensor readings can be broadcasted, logged to a file, or stored in a database.
  • Robust MySQL storage allows integrating with web visualizations and long term logging.
  • With many options for handling sensor data, the DHT22 is great for environmental IoT projects.

Conclusion

The low-cost DHT22 temperature and humidity sensor paired with a Raspberry Pi forms an excellent platform for various IoT and environmental monitoring projects. Interfacing the sensor is straightforward with the Adafruit Python library abstraction, and sensor data can be handled in different ways based on the application – from real-time broadcasting to robust database storage. Overall, the flexibility of reading, recording and storing DHT22 sensor data enables building Internet-connected environmental monitors for smart homes, offices buildings or any location that requires tracking temperature and humidity over time.

Frequently Asked Questions

  1. What is the DHT22 sensor?
    The DHT22 is an affordable digital humidity and temperature sensor capable of providing fairly precise temperature (±0.5°C) and humidity readings.

  2. How accurate is the DHT22?
    The DHT22 has a typical precision of ±1% relative humidity and as mentioned ±0.5°C for temperature.

  3. What Raspberry Pi pins are compatible with DHT22?
    The single-bus DHT22 can be connected to any unused GPIO pin on the Raspberry Pi. Software will handle communication.

  4. Is a resistor needed to connect DHT22 to Raspberry Pi?
    Yes, a 10 kiloohm pull-up resistor between the data line and 3.3V helps stabilize readings.

  5. Can DHT22 be powered from 5V GPIO?
    No. The DHT22 operates on 3.3V – it should only be connected to the 3.3V GPIO pins.

  6. What is typical humidity and temperature sensing range?
    0-100% RH with 1% precision for humidity. -40 to +80°C range for temperature readings with 0.5°C precision.

  7. How do I install the Adafruit DHT library?
    The library is installed through pip – run pip install adafruit–dht on your Raspberry Pi.

  8. Do I need to enable I2C interface?
    No, the DHT22 uses a simple single-bus data interface and does not require I2C.

  9. What is the data pin used for?
    The data line sends humidity and temperature readings to the Raspberry Pi when signaled to by the processor.

  10. Should cable length between sensor and Pi exceed a limit?
    It’s recommended to keep cables under 20 meters (~65 feet) long for reliable connectivity.

  11. How frequently can sensor data be retrieved?
    Temperature and humidity can be read as frequently as twice per second continuously when powered.

  12. Why is MySQL used instead of text file logging sometimes?
    A MySQL database provides more reliable storage for sensor data and allows creating web visualizations more easily.

  13. What real-life projects can use a DHT22 sensor?
    IoT weather stations, portable environmental data loggers, smart greenhouse monitoring, room climate control automation, and many more.

  14. Where can I buy a DHT22 sensor?
    The DHT22 and related accessories are available on most major online electronics retailers including AdaFruit, SparkFun, Seeed Studio, Amazon, and eBay.

  15. Is soldering required to connect wires to DHT22?
    The DHT22 pins are male header pins, allowing insertion of female jumper cables without any soldering.

  16. Can the DHT22 detect both temperature and humidity?
    Yes, the single-probe DHT22 digital sensor provides both ambient air temperature and percent relative humidity readings.

  17. How long can cable length be between DHT22 and Raspberry Pi?
    Cabling up to 20 meters (~65 feet) long still allows fairly reliable sensor connectivity. Keep cables short as possible.

  18. What GPIO pinouts are commonly used?
    Any unused GPIO pin will work, but common configurations use pin #4, #17 and #27 to connect the data line.

  19. What is the update rate for new readings?
    The DHT22 can provide new temperature and humidity readings up to twice per second continuously.

  20. What is the power draw of the sensor?
    Operating current is just 2.5 milliamps at 3-5V DC, allowing operation for months on batteries if paired with a low power system like Raspberry Pi Zero.

Leave a Comment