AM2302 Temp/Humidity Sensor with the Raspberry Pi

AM2302 Temp/Humidity Sensor with the Raspberry Pi

Wiring up the sensor

First things first, let’s connect the sensor to the Raspberry Pi.

  • Red wire connects to pin 1
  • Black wire connects to pin 6
  • Yellow wire connects to GPIO4 pin 7 (you can connect this wire to any of the GPIO pins, just make note of which one as we need to know which pin to listen on)

Installing the required software

The guys over at Adafruit have provided some software to interface with the sensor, which is available on github https://github.com/adafruit/Adafruit_Python_DHT.

Make sure you are in a suitable directory, e.g /home/pi

cd /home/pi

Then run the following commands:

git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT

Before we can install the python DHT library, there are a few dependencies that need installing.

sudo apt-get upgrade
sudo apt-get install build-essential python-dev

Once the dependencies have installed, we can move onto installing the library.

sudo python setup.py install

This should compile the code for the library and install it on your device so any Python program can access the Adafruit_DHT python module.

Testing the library

Now we have the DHT library installed, we can test the sensor by running one of the example programs.

First we need to change directory to the examples folder:

cd examples

Now we can run the AdafruitDHT.py program

sudo ./AdafruitDHT.py 2302 4

In this command you’ll see a couple of parameters:

2302 and 4

2302 is the sensor we are using

4 is the GPIO we are using (change this to whichever GPIO pin you hooked up the yellow wire to)

PLEASE NOTE: Sometimes you might see an error that the sensor can't be read and to try again, even if you have your connections setup correctly. This is a limitation of reading DHT sensors from Linux--there's no guarantee the program will be given enough priority and time by the Linux kernel to reliably read the sensor. If this occurs, run the program again (or call the read function again in your code) to try to get a new reading. In testing on both the Raspberry Pi & Beaglebone Black, about 75% of the read requests should generally succeed and return a result (assuming the board is not under heavy load).

If everything worked as it should you should see something similar to this:

Featured Products

The Pi Hut3-Way Fast Wire Connectors - Pack of 3
Sale price £3.50 incl. VAT excl. VAT

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.