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.

What’s Connected

Raspberry Pi

Dashboard Screenshots


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)

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:
        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)
    except (EOFError, SystemExit, KeyboardInterrupt):

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.

DHT11, DHT22 Sensors
DHT22 Support
Remote Access? How are people doing this with Cayenne
DHT11, DHT22 Sensors
Change default address of I2C sensor
Dht22/am2302 temp/humidity sensor
MQTT Manually Publishing / Subscribing
Support for other sensors
Running python at boot..problems
DHT11/DHT22 - temperature and humidity sensor
Fetch sensor data from Cayenne cloud API
Atlas PH sensor on rasberry pi and using I2C
Android app - MQTT not yet supported
Analog to digital converter input level multiplier
GSM signal
Push Button Support
Hall effect sensor on the raspi3
DHT11, DHT22 Sensors
New sensors with raspberry pi
MQTT Dash Phone Tool Setup Help
Temp sensor for heating tube
Grill temp sensor/probe
Max 31850k
Starting Gstreamer with Cayenne
Can we run our own python code from cayeene for raspberry pi 3
Modbus rtu & PLC comunications
Unable to configure Hall effect current sensor to Raspberry Pi 3b
DHT11, DHT22 Sensors
RPI connected to internet, but cayenne is offline since 5 hours
Sensor hygrometer and PH
Jessie on Orange Pi Plus 2

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.


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)


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



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)


Thanks for opening my eyes!
Very good explanation, adam…

best regards


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.



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


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


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.


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.


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.