The DHT11 temperature and humidity sensor is a nice little module that provides digital temperature and humidity readings. It’s really easy to set up, and only requires one wire for the data signal. These sensors are popular for use in remote weather stations, soil monitors, and home automation systems.
Connecting the DHT11 to the Raspberry
There are two types of the DHT11 sensor: one is a three pin module mounted on a PCB and the other is a four pin stand alone module. The pinout is different for each one, so connect your sensor following the image below.
THREE PIN DHT11
The wiring for the three pin module is like this:
- VCC: pin 2 of the Raspberry (5V)
- GND: pin 6 of the Raspberry (GND)
- Signal: pin 7 of the Raspberry (GPIO4)
FOUR PIN DHT11
The wiring for the four pin module is like this:
- VCC: pin 2 of the Raspberry (5V)
- GND: pin 6 of the Raspberry (GND)
- Signal: pin 7 of the Raspberry (GPIO4)
The resistor is a 10K Ohm connected between the Vcc and signal lines.
PROGRAMMING THE DHT11 WITH PYTHON
We’ll be using the Adafruit DHT11 Python library. You can download the library using Git, so if you don’t have Git installed on your Raspberry already, enter this at the command prompt:
sudo apt-get install git-core
To install the Adafruit DHT library:
Enter this at the command prompt to download the library:
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
Mount the directories with:
cd Adafruit_Python_DHT
Now enter this:
sudo apt-get install build-essential python-dev
Then install the library with:
sudo python setup.py install
The script:
Create a new file:
sudo nano temperature.py
Then copy this inside:
# -*- coding: utf-8 -*- import RPi.GPIO as GPIO import time import sys import Adafruit_DHT GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(4, GPIO.OUT) sensor_args = { '11': Adafruit_DHT.DHT11, '22': Adafruit_DHT.DHT22, '2302': Adafruit_DHT.AM2302 } if len(sys.argv) == 3 and sys.argv[1] in sensor_args: sensor = sensor_args[sys.argv[1]] pin = sys.argv[2] else: print('usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#') print('example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4') sys.exit(1) humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: print('Temperature={0:0.1f}°C Humidity={1:0.1f}%'.format(temperature, humidity)) else: print('Failed to get reading. Try again!') sys.exit(1)
To run the script you have to write:
sudo python temperature.py 11 4
- 11: the type of sensor (11) because you can use this script with the DHT22 (22)
- 4: the GPIO port; if you connect the sensor to another GPIO you have to change this number
This Python program will output the temperature and humidity to an SSH terminal.
Check out how to misure a distance with HC-SR04