Legacy post. This article was written between 2016 and 2018. Software versions, commands and services mentioned here may be outdated. Check the official documentation before running anything.
The goal of this tutorial is to write a program that reads from a DHT22 sensor.
Prerequisites
- Components < 70 EUR:
| Component | Site | Price |
|---|---|---|
| Raspberry PI 3 | Farnell | 37.69 EUR |
| Power supply Micro USB 5V 2500mA | Amazon | 8.99 EUR |
| Micro SD Card (16 Go class 10) | Amazon | 9.99 EUR |
| DHT22 Sensor | ebay | 5.60 EUR |
| Breadboard | ebay | 3.30 EUR |
| 10 x Cables male/female | ebay | 1.00 EUR |
| 10 x Cables male/male | ebay | 1.00 EUR |
| 10 x Resistors 10k | ebay | 1.10 EUR |
| Total: | 68.67 EUR |
Note: This is only an example. You can buy the components from other sites, and maybe at better prices.
Electronic wiring
Install Adafruit
Adafruit is a Python library that reads the DHT series of humidity and temperature sensors on a Raspberry Pi.
Download the latest version
wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip
Unzip the package
unzip master.zip
Installation
cd Adafruit_Python_DHT-master/
sudo python setup.py install
See more here
or in a virtual environment
virtualenv -p /usr/bin/python2.7 ~/workspace/venv2.7/
source ~/workspace/venv2.7/bin/activate
pip install adafruit_python_dht
See how to create a virtual environment here
Get Series of data
Get a series of temperature and humidity readings from the DHT22
Create new script
touch getDHT22Series.py
Edit the file and add the code below
vim getDHT22Series.py
#!/usr/bin/python
import Adafruit_DHT
def getData_func():
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)
if humidity is not None and temperature is not None:
print('Temperature={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
return { '@type':'DHT22', 'temperature': temperature, 'humidity': humidity }
else:
print('Failed to get reading. Try again!')
return
if __name__ == "__main__": getData_func()
See source here
Execute the code
python getDHT22Series.py
Output:
Temperature=23.8*C Humidity=36.3%