DHT11/DHT22 with Raspberry Pi

About This Project

This project will read temperature and humidity from a DHT11 or DHT22 sensor and send the values to Cayenne using MQTT. The python MQTT client and Adafruit DHT sensor library will need to be installed for this script to run. Install the software prerequisites using the commands below:

sudo pip install paho-mqtt
sudo apt-get install build-essential python-dev python-openssl
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
sudo python setup.py install

Wire the DHT11 as the picture below. The resistor is a 4.7k. The GPIO pin you connect to does not matter. In the example code below I used GPIO pin 17.


Wire the DHT22 as in the picture below. Again, the resistor is a 4.7k and the GPIO pin does not matter. In the example code below I used GPIO pin 18.

breadboard_dht22

Whatā€™s Connected

Raspberry Pi
DHT11
DHT22

Dashboard Screenshots

Code

import paho.mqtt.client as mqtt
import time
import sys
import Adafruit_DHT

time.sleep(30) #Sleep to allow wireless to connect before starting MQTT

username = "MQTT Username From Dashboard"
password = "MQTT Passsword From Dashboard"
clientid = "MQTT Client ID From Dashboard"

mqttc = mqtt.Client(client_id=clientid)
mqttc.username_pw_set(username, password=password)
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)
mqttc.loop_start()

topic_dht11_temp = "v1/" + username + "/things/" + clientid + "/data/1"
topic_dht11_humidity = "v1/" + username + "/things/" + clientid + "/data/2"
topic_dht22_temp = "v1/" + username + "/things/" + clientid + "/data/3"
topic_dht22_humidity = "v1/" + username + "/things/" + clientid + "/data/4"

while True:
    try:
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number (not physical pin number)
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number (not physical pin number)
        
        if temp11 is not None:
            temp11 = "temp,c=" + str(temp11)
            mqttc.publish(topic_dht11_temp, payload=temp11, retain=True)
        if humidity11 is not None:
            humidity11 = "rel_hum,p=" + str(humidity11)
            mqttc.publish(topic_dht11_humidity, payload=humidity11, retain=True)
        if temp22 is not None:
            temp22 = "temp,c=" + str(temp22)
            mqttc.publish(topic_dht22_temp, payload=temp22, retain=True)
        if humidity22 is not None:
            humidity22 = "rel_hum,p=" + str(humidity22)
            mqttc.publish(topic_dht22_humidity, payload=humidity22, retain=True)
        time.sleep(5)
    except (EOFError, SystemExit, KeyboardInterrupt):
        mqttc.disconnect()
        sys.exit()

Save this file to /home/pi/python/tempsensor.py (path does not matter, just be sure to update path to match yours throughout the next steps) and fill in your username, password, and client id (lines 8, 9, 10). You can also delete the DHT11 or DHT22 lines based on which sensor you are using or add additional lines to check more than 1 sensor. The topic_dht lines will all need unique channels, so be sure the last digit in the string is unique "v1/username/things/clientid/data/ 1 "

For testing just run the file with python /home/pi/python/tempsensor.py After it is working correctly add the widget to the dashboard permanently by clicking the + in the upper right hand. Add the python file to your crontab with sudo crontab -e then type in @reboot python /home/pi/python/tempsensor.py & and save. Reboot and you should see the values populate on your MQTT dashboard. To remove the script use the command sudo crontab -e again and either put a # in front of the @reboot line you added, or delete it entirely.

10 Likes

Thank you very much.

I just have a questions because im new to this whole MQTT thingy.

Do we have to insert any Login Data at this part?

greetings from Germany

Yep, this is the info from your MQTT dashboard. When you click Add Newā€¦>Device/Widget>Bring Your Own Thing button it will display everything for you. You will also have to replace username and clientid in the topic_dht lines right below that.

1 Like

Hello adam, your Support is much appreciated :slight_smile:

I have another question: If i want to use more than one DHT22 i only have to copy the Scriptfile, change the GPIO Pin, change the file name & add a second (@Reboot) line to the Crontabā€¦right?

In short: One Script for every DHT22 i want to add

thx in advance

You can do that but I would keep it as one script and add to it. So add a new topic_dht line for each additional sensor making sure to keep unique channels for each (the last digit in the string) and then add additional lines to check the sensors humidity11, temp11 = Adafruit_DHT.read_retry(11, 17)

1 Like

Hello to everybody,

Iā€™m a pretty greenhorn to all concerning to linux et.

For now Iā€™m asking for your help.

Iā€™m trying out to add a DHT11 to my RaspPi 3.

I followed exactly all steps written by adam but my MQTT - Dashboard always hangs up at ā€œWaiting for board to connectā€¦ā€

I recognized, that the client-id changes always when the mttq - dashboard is started new.

Is this ok? So what ID should I insert into tempsensor.py

thank you for helping

best regards from Germany

Martin

1 Like

Yes, the clientid will be listed on each new MQTT device you create (maybe also new username/password? Iā€™m not sure about that though) Fill in your username, password, and client id wherever required in the .py file (lines 8, 9, 12, 13, 14, 15 in the original file)

1 Like

Thanks for opening my eyes!
Very good explanation, adamā€¦

best regards
Martin

1 Like

Hi there! thank you very much for this awsome guide! It worked really nicely in my case. The only problem is that when I try to have Graph representation for anything but ā€œliveā€ then it doesnt really update values. It only shows this circular dots as if something is loading. Interestingly, as soon as I switch back to ā€œliveā€ then the Graph work again.

I dont know if this is problem of this particular set up or cayenneā€™s.

thanks!

1 Like

I had the same thing. Unfortunately graph history isnā€™t available for MQTT yet but itā€™s on the road map.

2 Likes

Hello adam,

I also try your code here with DHT11 sensor only. I am with raspberry 3. This is the command line error when I try to run my file testDHT.py:

Traceback (most recent call last):
  File "testDHT.py", line 17, in <module>
    humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
  File "/home/pi/Adafruit_Python_DHT/Adafruit_DHT/common.py", line 90, in read_retry
    humidity, temperature = read(sensor, pin, platform)
  File "/home/pi/Adafruit_Python_DHT/Adafruit_DHT/common.py", line 76, in read
    platform = get_platform()
  File "/home/pi/Adafruit_Python_DHT/Adafruit_DHT/common.py", line 51, in get_platform
    from . import Raspberry_Pi_2
  File "/home/pi/Adafruit_Python_DHT/Adafruit_DHT/Raspberry_Pi_2.py", line 22, in <module>
    from . import Raspberry_Pi_2_Driver as driver
ImportError: cannot import name Raspberry_Pi_2_Driver

Something that makes me sad is that it give error about some RPI 2 drivers, and I am using RPI 3.

Something interesting - when I goes into the DHT library and then into examples, when I write the following:

python AdafruitDHT.py 11 17

it is showing the current temp and humidity.

I move my file with your code into this folder (examples) and when I try to execute it, the cursor is just staying and nothing happens.

Hmm thatā€™s definitely odd. Did you follow the install procedure for the library?

sudo apt-get install build-essential python-dev python-openssl
git clone https://github.com/adafruit/Adafruit_Python_DHT.git22
cd Adafruit_Python_DHT
sudo python setup.py install

1 Like

Yes, I strictly follow the procedure.
This is how it looks like, when I try to run the script. And in the Dashboard, the device is added, but with NO widgets.

Hit refresh on the dashboard while the script is running and let me know if you see anything show up.

1 Like

No, nothing is showed up :frowning:

Can you PM me the exact script your using? I can test later to see if you see the values show up on your dashboard.

1 Like

Thanks to adam, I was forget to change topic_dht11_temp credentials. I only change the username, not the cliendid.

Thank you all guys!!!

The tutorial worked just fine for me, butā€¦
ā€¦after a few Hours the DHT22 appears offline in the Dashbard.
My Rpi3 runs 24/7. With one Reboot per Day in the morning.(Because of the Memory usage rising to 95%+)

And everytime i check it (in the afternoon) the DHT22 seams to be Offline for 6-8 hours
Is there a log i could look in to?

If you can log in to the pi you can delete the cron job with crontab -e then open the terminal and start the script with python file.py and then just leave the terminal window open to see if you get any errors. Iā€™m having some problems with my pi as well but I think the log file filled up my SD card again.