• About
  • Advertise
  • Privacy & Policy
  • Contact
Raspberry Pi Developing
  • Home
  • Getting Started
    Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

    Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

    All About Batteries

    All About Batteries

    What’s The Difference Between DC, Servo & Stepper Motors?

    What’s The Difference Between DC, Servo & Stepper Motors?

    Which OS is Best for Raspberry PI ?

    Which OS is Best for Raspberry PI ?

  • Pi Projects

    Raspberry Pi UV Sensor using the VEML6075

    Raspberry Pi Nvidia Shield: Stream Games using Moonlight

    Raspberry Pi Accelerometer using the ADXL345

    Raspberry Pi Accelerometer using the ADXL345

    Raspberry Pi Humidity Sensor using the DHT22

    Raspberry Pi Humidity Sensor using the DHT22

  • How to
    Setting up Home Assistant on the Raspberry Pi

    Setting up Home Assistant on the Raspberry Pi

    How to Install PHPMyAdmin on the Raspberry Pi

    How to Install PHPMyAdmin on the Raspberry Pi

    Setup a Raspberry Pi MYSQL Database

    Setup a Raspberry Pi MYSQL Database

    How to Upgrade Raspbian Stretch to Raspbian Buster

    How to Upgrade Raspbian Stretch to Raspbian Buster

    How to Setup Raspberry Pi RecalBox

    Play Retro Games with Raspberry Pi RetroPie

    Trending Tags

    • Arduino Projects
      RS-485 Serial Communication between Raspberry Pi and Arduino Uno

      RS-485 Serial Communication between Raspberry Pi and Arduino Uno

      Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

      Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

      The 2019 Thermostat ReThink

      The 2019 Thermostat ReThink

      Tracked Arduino Robot

      Tracked Arduino Robot

    • News
      New report shows how IoT devices remain under ‘constant’ attack

      New report shows how IoT devices remain under ‘constant’ attack

      BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

      BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

      Raspberry Pi Comparison Table

      Raspberry Pi Kernel Updated to 4.19

      Apple Watch Series 2 Is Swimproof and Comes With Built-In GPS

      To regain advertiser trust, Facebook is tracking ads by the millisecond

      National Academy of Sciences endorses embryonic engineering

      Trending Tags

      No Result
      View All Result
      • Home
      • Getting Started
        Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

        Getting started with Node.js and Raspberry Pi: Controlling an LED with Node.js Webserver

        All About Batteries

        All About Batteries

        What’s The Difference Between DC, Servo & Stepper Motors?

        What’s The Difference Between DC, Servo & Stepper Motors?

        Which OS is Best for Raspberry PI ?

        Which OS is Best for Raspberry PI ?

      • Pi Projects

        Raspberry Pi UV Sensor using the VEML6075

        Raspberry Pi Nvidia Shield: Stream Games using Moonlight

        Raspberry Pi Accelerometer using the ADXL345

        Raspberry Pi Accelerometer using the ADXL345

        Raspberry Pi Humidity Sensor using the DHT22

        Raspberry Pi Humidity Sensor using the DHT22

      • How to
        Setting up Home Assistant on the Raspberry Pi

        Setting up Home Assistant on the Raspberry Pi

        How to Install PHPMyAdmin on the Raspberry Pi

        How to Install PHPMyAdmin on the Raspberry Pi

        Setup a Raspberry Pi MYSQL Database

        Setup a Raspberry Pi MYSQL Database

        How to Upgrade Raspbian Stretch to Raspbian Buster

        How to Upgrade Raspbian Stretch to Raspbian Buster

        How to Setup Raspberry Pi RecalBox

        Play Retro Games with Raspberry Pi RetroPie

        Trending Tags

        • Arduino Projects
          RS-485 Serial Communication between Raspberry Pi and Arduino Uno

          RS-485 Serial Communication between Raspberry Pi and Arduino Uno

          Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

          Installing and Testing Mosquitto MQTT Broker on Raspberry Pi for IoT Communication

          The 2019 Thermostat ReThink

          The 2019 Thermostat ReThink

          Tracked Arduino Robot

          Tracked Arduino Robot

        • News
          New report shows how IoT devices remain under ‘constant’ attack

          New report shows how IoT devices remain under ‘constant’ attack

          BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

          BlackBerry, Telus, L-Spark among those to launch programme for Canadian IoT startups

          Raspberry Pi Comparison Table

          Raspberry Pi Kernel Updated to 4.19

          Apple Watch Series 2 Is Swimproof and Comes With Built-In GPS

          To regain advertiser trust, Facebook is tracking ads by the millisecond

          National Academy of Sciences endorses embryonic engineering

          Trending Tags

          No Result
          View All Result
          Raspberry Pi Developing
          No Result
          View All Result

          Raspberry Pi Humidity Sensor using the DHT22

          tibi by tibi
          May 14, 2019
          Home Pi Projects
          Share on FacebookShare on Twitter

          In this Raspberry Pi humidity sensor tutorial, we will show you how to connect the DHT22 sensor to the Raspberry Pi and how you can use Python to read data from the sensor.

          Raspberry Pi Humidity Sensor

          The DHT22 is a versatile and low-cost humidity sensor that can also calculate the temperature of an area.

          This sensor has a relatively long transmission distance, allowing the sensor to transmit data through wires up to 20m away from the Raspberry Pi.

          As a bonus, the DHT22 is a digital sensor with an inbuilt analog to digital converter. The converter makes it a lot easier to connect the sensor to the Raspberry Pi as you do not need to deal with any additional chips.

          The biggest downside to the DHT11 and DHT22 sensors is that they are quite slow sensors. They have a sampling rate of once every second for the DHT11 and once every 2 seconds for the DHT22.

          You can also use the DHT22 with the Arduino, so be sure to check that tutorial if you would rather use an Arduino board.

          While this tutorial covers connecting the DHT22 to the Raspberry Pi, it will also work with the DHT11 and AM2302 humidity sensors as they all use the same pinouts.

           Equipment

          Below is all the equipment that you will need for connect the DHT22 Humidity Sensor to your Raspberry Pi.

          Recommended

           Raspberry Pi

           8GB SD Card or Micro SD Card if you’re using a Raspberry Pi 2, 3 or B+

           Breadboard wire

           DHT22 Humidity Sensor

           10k ohm resistor (Brown, Black, Orange, Gold)

          Optional

           Raspberry Pi Case

           Video

          The video below will take you through the steps to assembling the humidity circuit and how to connect it to your Raspberry Pi. It also covers the steps on how to write a simple Python script to talk with the DHT22 sensor.

          If you prefer a written tutorial. then you can find that right underneath the video.

          Can’t see the video? Support us by disabling your adblocker.

           Raspberry Pi Humidity Sensor Hardware Setup

          In this section of the tutorial, we will show you the process on how to connect your DHT22 humidity sensor to the Raspberry Pi.

          Thanks to the DHT22 being a digital sensor, it is incredibly straightforward to connect to the Raspberry Pi. The single data pin is able to connect directly to the Raspberry Pi’s GPIO pins.

          You can follow our guide below to see how to connect the DHT22 to your Raspberry Pi.

           DHT22 Pinout

          To make things easier when assembling the humidity sensor circuit we have included the pinout of the DHT22 sensor.

          This diagram should help you work out where each pin needs to go on the Raspberry Pi.

          • Pin 1 is VCC (Power Supply)
          • Pin 2 is DATA (The data signal)
          • Pin 3 is NULL (Do not connect)
          • Pin 4 is GND (Ground)
          DHT22 Temperature Sensor with numbering

           Raspberry Pi DHT22 Circuit

          Here we have included a couple of ways you can put the Raspberry Pi Humidity sensor circuit together.

          You can either rely on our two diagrams below to see what pins need to go to what or use our written steps below.

          • Place a 10k resistor between Pin 1 and Pin 2 of the DHT22
          • Wire Pin 1 of the DHT22 to Physical Pin 1 (3v3) on the Pi
          • Wire Pin 2 of the DHT22 to Physical Pin 7 (GPIO4) on the Pi
          • Wire Pin 4 of the DHT22 to Physical Pin 6 (GND) on the Pi
          Raspberry Pi Humidity Sensor DHT22 Wiring Schematic
          Raspberry Pi Humidity Sensor DHT22 GPIO Pins

           Preparing the Raspberry Pi to talk with the Humidity Sensor

          1. Before we get started with programming a script for the Raspberry Pi humidity sensor, we must first ensure that we have the latest updates on our Raspberry Pi.

          We can do this by running the following two commands to update both the package list and installed packages.

          sudo apt-get update
          sudo apt-get upgrade

          2. With our package list now up to date, we need to go ahead and install both python 3and pip. We will be using both of these packages to interact with our humidity sensor.

          Install both python3-dev and python3-pip by running the command below.

          sudo apt-get install python3-dev python3-pip

          3. Before we go ahead and install the DHT library, we should first run the following command to ensure we have the latest versions of the setuptools, wheel and pip python packages.

          sudo python3 -m pip install --upgrade pip setuptools wheel

          4. Now using pip, we will go ahead and install Adafruit’s DHT library to the Raspberry Pi.

          We will be using this Python library to interact with our DHT22 Humidity/Temperature sensor.

          As a bonus, the library also supports the DHT11 and AM2302 humidity/temperature sensors making it a great library to learn how to utilize.

          Run the following command to install the DHT library to your Raspberry Pi.

          sudo pip3 install Adafruit_DHT

          5. In the next section of our Raspberry Pi humidity sensor tutorial, we will show you how you can put this library to use and utilize it within a python script to talk with the DHT22 sensor.

           Programming for the Raspberry Pi humidity sensor

          1. Now that we have installed the Adafruit DHT library to our Raspberry Pi we can now proceed to program with it.

          First, we must make a Python script in which we will store all our code. To begin writing this file, you can enter the following command into your Raspberry Pi.

          nano ~/humidity.py

          2. Within this file, we need to enter the following lines of code. We will explain each section of the code as we go along.

          import Adafruit_DHT

          This line imports the “Adafruit_DHT” library that we obtained using pip in the previous section.

          We will be using this library to talk and interact with the DHT22 sensor. The library allows us to very easily retrieve the temperature and humidity from the sensor with a few lines of python code.

          DHT_SENSOR = Adafruit_DHT.DHT22

          On this line, we define a constant for the sensor that we want to utilize for the DHT Library. The Adafruit DHT library has three choices that you can choose from depending on the sensor used.

          For this tutorial, we are making use of the DHT22, so we defined our “DHT_SENSOR” constant as “Adafruit_DHT.DHT22“.

          If you are following this guide but are using either the DHT11 or the AM2302 you can use either “Adafruit_DHT.DH11” or “Adafruit_DHT_AM2302” respectively.

          DHT_PIN = 4

          Next, we define a constant called “DHT_PIN” this is to store the number of the GPIO pin that the DHT22 is plugged into on the Raspberry Pi.

          The number we use refers to the BCM numbering of the GPIO pins. In our tutorials case, this means we need to use the number “4” as we utilized the GPIO4 pin for our data connection.

          If you utilized a different GPIO pin, then make sure you update this number accordingly.

          while True:
              humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

          Next, we start up an infinite loop by using the “while TRUE:” code. This loop will continually run until a user kills the Python script.

          At the start of every loop, we utilize the Adafruit DHT library to retrieve both the humidity and temperature from the DHT22 sensor, specifying both our DHT_SENSOR and DHT_PINconstant.

          The “read_retry” function will continually try to retrieve the data from the humidity sensor.

              if humidity is not None and temperature is not None:
                  print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(temperature, humidity))
              else:
                  print("Failed to retrieve data from humidity sensor")

          Finally, we check to ensure that the DHT library returned data that is useful to us.

          If either the “humidity” or “temperature” variables are “None” then we return a message telling the end user that we failed to retrieve data from our humidity sensor.

          If we did have values in both of those variables, then we print out a message showing the end user both the temperature and the humidity that we just retrieved from our humidity sensor.

          3. Once you have finished entering the code, it should look like what we have displayed below.

          import Adafruit_DHT
          
          DHT_SENSOR = Adafruit_DHT.DHT22
          DHT_PIN = 4
          
          while True:
              humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
          
              if humidity is not None and temperature is not None:
                  print("Temp={0:0.1f}*C  Humidity={1:0.1f}%".format(temperature, humidity))
              else:
                  print("Failed to retrieve data from humidity sensor")

          4. When you are happy that all the code you entered is correct you can then save the file by pressing CTRL + X, then Y followed by ENTER.

          5. With the script now saved, let’s go ahead and run it so that we can start to see the data from the humidity sensor.

          You can run this script by running the following command.

          python3 ~/humidity.py

          6. From this command, you should start seeing results like what we have below. The temperature and the humidity should be displayed through the command line.

          Temp=25.6*C  Humidity=51.8%
          Temp=25.2*C  Humidity=45.4%
          Temp=25.1*C  Humidity=45.4%
          Temp=25.0*C  Humidity=45.3%

          7. In the next section of the tutorial, we will show you how you can modify this script so that it logs the data to a file. The file will be able to be read by a program such as Microsoft Excel or Google Spreadsheets.

           Logging the Data from the Raspberry Pi Humidity Sensor

          1. Let’s start by creating a new script. This script will be somewhat similar to our previous script but with a few changes made so that we can write to a file.

          Start by running the following command to begin writing our new script.

          nano ~/humidity_logger.py

          2. Within this file enter the following lines. We will only be explaining the new additions to the script in this section.

          import os
          import time
          import Adafruit_DHT

          Here we add the import for both the “os” and “time” libraries. We utilize the “os” library so we can check if our CSV file exists before we try to write to it.

          We use the “time” library so that we can timestamp each new row with the current date and time.

          DHT_SENSOR = Adafruit_DHT.DHT22
          DHT_PIN = 4

          There is no difference with these two lines, keep them as you had in the previous script.

          try:
              f = open('/home/pi/humidity.csv', 'a+')
              if os.stat('/home/pi/humidity.csv').st_size == 0:
                      f.write('Date,Time,Temperature,Humidity\r\n')
          except:
              pass

          Here we wrap everything within a try statement to handle any potential errors.

          We open up a handle to our “/home/pi/humidity.csv” file with the “a+” tag applied. The a+ tag means that any data written to the file will be appended to the end of it.

          Next, we use the “os” library to see if we have ever written to this file before. If the size returns as 0 we then write an initial line to the file. This line will contain our column headers so you can understand the data easier.

          while True:
              humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)

          Here we have our while loop again. We utilize the DHT Library to read data from our DHT22 humidity sensor again.

          This function will store the data it reads from the sensors into our “humidity” and “temperature” variables.

              if humidity is not None and temperature is not None:
                  f.write('{0},{1},{2:0.1f}*C,{3:0.1f}%\r\n'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M'), temperature, humidity))  
              else:
                  print("Failed to retrieve data from humidity sensor")
          
              time.sleep(30)

          Our big change to this section of code is that instead of printing the temperature and humidity to the console, we write it to our “humidity.csv” file. We do this by using the file handle we opened earlier.

          We format the text written to the file to include both the current date, current time, our formatted temperature and humidity.

          At the end of the loop, we sleep the script for 30 seconds, if you want to make it sleep longer or poll more often then modify this number.

          3. Once you have finished entering the code, it should look like what we have displayed below.

          import os
          import time
          import Adafruit_DHT
          
          DHT_SENSOR = Adafruit_DHT.DHT22
          DHT_PIN = 4
          
          try:
              f = open('/home/pi/humidity.csv', 'a+')
              if os.stat('/home/pi/humidity.csv').st_size == 0:
                      f.write('Date,Time,Temperature,Humidity\r\n')
          except:
              pass
          
          while True:
              humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
          
              if humidity is not None and temperature is not None:
                  f.write('{0},{1},{2:0.1f}*C,{3:0.1f}%\r\n'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M'), temperature, humidity))
              else:
                  print("Failed to retrieve data from humidity sensor")
          
              time.sleep(30)

          4. Once done, save the file by pressing CTRL + X, then Y followed by ENTER.

          5. Now like our last script lets go ahead and now run it by entering the following command.

          python3 ~/humidity_logger.py

          6. Once you exit out of the script, you will now be able to check out the “humidity.csv” file to see all the results that you have logged over time.

          If you run the following command, you should see the contents of the file.

          nano ~/humidity.csv

          7. Below is an example of the contents that you should see within this file.

          Date,Time,Temperature,Humidity
          05/04/19,05:47,22.3*C,50.6%
          05/04/19,05:48,22.2*C,50.4%
          05/04/19,05:48,22.2*C,50.6%
          05/04/19,05:49,22.2*C,50.4%
          05/04/19,05:49,22.2*C,50.4%
          05/04/19,05:50,22.2*C,50.3%
          05/04/19,05:50,22.2*C,50.3%
          05/04/19,05:51,22.2*C,50.2%

          Once you have verified that the file is successfully being written, then you are finally done with programming your Raspberry Pi humidity sensor.

          If you need a waterproof temperature sensor, then be sure to check out our DS18B20 temperature sensor tutorial. It covers everything you need to know, and it works perfectly alongside this sensor.

          I hope that everything has worked correctly for you and you’re not collecting the humidity and temperature without issues. If you want to leave some feedback, then please don’t hesitate to leave a comment below.

          Tags: dht22humidityraspberrysensorusing
          tibi

          tibi

          Next Post
          Raspberry Pi Accelerometer using the ADXL345

          Raspberry Pi Accelerometer using the ADXL345

          Comments 1

          1. Lúcio Couto says:
            1 year ago

            Hi All,
            I’d like to congratulate you all on your great job by sharing information through this channel.
            I’m starting to use raspberry pi for continuous learning purposes. When trying this example code everything works good but the humidity.csv file doesn’t store the information from DHT22 sensor. The file is saved empty without any data.
            Can you kindly advise how to fix that problem? Thanks in advance.

            Reply

          Leave a Reply Cancel reply

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

          Recommended.

          Raspberry Pi Port Forwarding & Dynamic DNS

          Raspberry Pi Port Forwarding & Dynamic DNS

          March 16, 2019
          Solar Powered Raspberry Pi

          Solar Powered Raspberry Pi

          April 11, 2019

          Trending.

          How to Setup a Raspberry Pi Nextcloud Server

          How to Setup a Raspberry Pi Nextcloud Server

          March 14, 2019
          How to Setup a Raspberry Pi NAS (Network Attached Storage)

          How to Setup a Raspberry Pi NAS (Network Attached Storage)

          April 13, 2019
          Raspberry Pi TorrentBox: Build an Always-On Torrent Machine

          Raspberry Pi TorrentBox: Build an Always-On Torrent Machine

          March 16, 2019
          Setup a Raspberry Pi MYSQL Database

          Setup a Raspberry Pi MYSQL Database

          July 28, 2019
          Raspberry Pi Humidity Sensor using the DHT22

          Raspberry Pi Humidity Sensor using the DHT22

          May 14, 2019
          Raspberry Pi Developing

          PI Guide Developing is where you can find some of the coolest Raspberry Pi projects and guides on the web. You can check them all out right here.

          Follow Us

          Categories

          • Arduino Projects
          • Getting Started
          • How to
          • News
          • Pi Projects

          Tags

          about adding Apple Watch 2 arduino beginners Best iPhone 7 deals build Buying Guides camera CES 2017 clock digital display drive email games getting guide install installing iOS 10 iPhone 7 learn linux mount mysql network Nintendo Switch phpmyadmin Playstation 4 Pro python raspberry Raspbian sense sensor server setting setup Sillicon Valley simple started storage system tutorial using

          Recent News

          Setting up Home Assistant on the Raspberry Pi

          Setting up Home Assistant on the Raspberry Pi

          March 22, 2020
          How to Install PHPMyAdmin on the Raspberry Pi

          How to Install PHPMyAdmin on the Raspberry Pi

          July 28, 2019
          • About
          • Advertise
          • Privacy & Policy
          • Contact

          © 2019 PI GUIDE - Premium PI Guide PI GUIDE.

          No Result
          View All Result
          • Home
          • Getting Started
          • How to
          • Pi Projects
          • Arduino Projects
          • News

          © 2019 PI GUIDE - Premium PI Guide PI GUIDE.