Read a DHT sensor on Raspberry Pi and mqtt the results

In an earlier post I showed how one could address the raspberry GPIO pins, in fact that is quite straightforward given the fact they are digital I/O pins that either are HIGH or LOW.
But what if one wants to read a sensor like a DHT11 attached to one of the GPIO pins? That is also not so difficult, but to make it more all round and easy to use in OpenHAB, I wanted to read a sensor and then MQTT the result to my MQTT broker.
In my case, my MQTT broker is on the same raspberry that I also aimed to attach the DHT11 to, so if I wanted I could read it directly, but just in case I wanted to read it from another raspberry, MQTT is a better solution (for me).

As it is no use to re-invent the wheel, I fortunately found someone already had done most of the work, albeit for a DHT22, but that was easy to alter.

For the next steps I presume you already have python installed. Jessie already should have python 2.7 installed, and should you want to upgrade that, check here.
The Python program calls a few libraries that you most likely already have, maybe with exception of the paho.mqtt.client and the adafruit DHT library.
the mqtt client can be installed as follows:*)
pip install paho-mqtt
if for whatever reason this does not work for you, try:
git clone => download the client
cd paho.mqtt.python => go to proper directory
python install => install the client
depending on how you are logged in you may need to add ‘sudo’ before the install commands

The mqtt client is now installed.

For the DHT library do the following:
git clone => download the library
cd Adafruit_Python_DHT => go to proper directory

Before you install the library, you need some dependencies that may or may not be on your system:
sudo apt-get update
sudo apt-get install build-essential python-dev python-openssl
If you already had modules installed those will be skipped.
Then install the library:
sudo python install => install the library

At this moment it is a good idea to restart your raspberry.
If you want -when your raspberry is back up and running- you could now try one of the example programs in the Adafruit DHT library, just to make sure everything is working.
Connect your DHT11 to e.g. GPIO4 of your raspberry.
Make sure you are still in  directory: Adafruit_Python_DHT

cd examples
sudo ./ 11 4

You will get the temperature and Humidity reported in your terminal

Now download the DHT_sensor program.
If like me you want to use a DHT11 instead of a DHT22, change line 45:
DHT_TYPE = Adafruit_DHT.DHT22
DHT_TYPE = Adafruit_DHT.DHT11

and save the program on your raspberry

I saved it directly in my home/openhabian directory, i.e. the directory that is availble directly after logon

Now have a look at the usage instructions in the program (lines 36-42), but beware:
Presuming you saved the program as “”, that is the name you need to use instead of “” (the name mentioned in the “Usage”).
I started my program as follows:

./ 'cupboard/temperature1' 'cupboard/humidity1' 4

This says that as my mqtt topics I have cupboard/temperature1 and cupboard/humidity1 and my DHT11 sensor is attached to GPIO pin 4 while the refresh rate is 300 seconds (the default).

To make it a bit easier I created a file called “” that contained the single line:
./ 'cupboard/temperature1' 'cupboard/humidity1' 4 50
That does the same as the earlier line, but now I set the refresh rate to 50 seconds. I put it in one file because that is easier to type.
If you want you can make the file to automatically start at boot as I describe below.

The MQTT messages are subsequently sent out over the network

And one could use definitions like below in your OpenHAB Items file to use them in OpenHAB

Number Cupboard_temp "Riser temperatuur [%.1f °C]" <temperature> (GF_Corridor) {mqtt="<[mosquitto:cupboard/temperature1:state:default]"}
Number Cupboard_humidity "Riser humidity [%.0f %%]" <line> (GF_Corridor) {mqtt="<[mosquitto:cupboard/humidity1:state:default]"}
Starting the script at boot

The script will run perfectly when started manually, but it will run in an instance of the SSH window and the moment you close that window, the script will stop. It is therefore better to have the script starting at boot. This is simple to do, but you have to be aware of the full PATH you are using.
Change the content of the dht.s file as follows:
Then in your preferred editor open the etc/rc.local file and add a line (the line at the red arrow):
Save the file and reboot. You will now no longer see the temperature and humidity in an ssh window, but the MQTT commands are being sent.

As this program sends its results by MQTT it can be used on other raspberry’s as well, noit just the one you have your openhabian and or MQTT broker installed on. Be sure though that if you install it on another raspberry, you alter the ‘servername’  variable into the name or ip address of the  MQTT broker

A word of warning:
If you are eager to test the program, before you  connected a sensor, it will just skip the sensor and you will get no useful feedback.
Furthermore, Python is quite sensitive to using the proper indentation in its programs as these have a meaning  in how the program is being interpreted, so if you go edit the program, be sure to keep the proper indentation

Added: Errors
If you install the above on an openhabian system you are unlikely to get any errors. However, I tested it on a freshly installed raspian Stretch system (not sure anymore if it was ‘Lite’) and I came upon the following Errors that were easy to fix:
-bash: git: command not found
sudo apt-get install git
File “”, line 5, in
from setuptools import setup, find_packages
ImportError: No module named setuptools
sudo apt-get install python-setuptools
no module named requests
sudo pip install requests
No pip
apt install python-pip #python 2
Append error, logging in again: [Errno -2] Name or service not known
Most likely you are running the file from another raspbery where your MQTT server is not located. Make sure you alter the variable ‘servername’ in the file into the servername or ip number where your mqtt broker is situated. Also make sure you do not have two clients running with the same name.

“no module named Adafruit_DHT”
Go to the Adafruit_Python_DHT folder and do:
sudo python install --force



*) I could have used the mosquitto client that was on my raspberry that was already functioning as a broker, but as I also wanted to use it on other raspberries, it was better to use the lightweight paho.mqtt.client


9 thoughts on “Read a DHT sensor on Raspberry Pi and mqtt the results”

  1. As I am phasing out my Oregon Scientific weather station, I have been thinking about this entire issue a bit. I came to a different solution (not better, just different).

    A) ditch the DHT sensor. They are not very reliable, neither do they have good endurance. Protocol is well known but “weird”. I went for the BMW280 on I2C, which gives me barometric pressure as a bonus.

    B) do not mount it on/near a running computer board-chip but on a dedicated ESP8266, for the following reasons:

    1) I run Mosquitto on my Synology NAS. No “now too big for the project” Pi available! And if I did have one, it would probably be mounted in the utility closet doing “things”.

    2) Heat! The sensor should be mounted away from the chips.

    3) To circumvent 1 and 2 of course I could do cable runs, but in all honesty, that is the last thing I want to do.

    I will implement this probably on an ESP-01 in deep sleep mode. MQTT, battery friendly and no heat. Maybe the outside one I will add a small solar panel, not sure yet.

    1. I fully agree. I however still have some DHT’s that I use to get a general reading of my various rooms, but I have to admit that I also use a ds18B20. The BME280 is alltogether a better choice and I will use that outside (still waiting for it to arrive, chinese newyear), although supposedly the temp supposedly can have a bit of a drift as the chip ‘gets warm’.I however do not believe that is a huge problem especially not if there are no continuous readings.

      Adding the DHT to the Raspi and using MQTT is on the one hand more of an excercise, whereas the fact I am using MQTT allows for use of a seperate Raspi ‘doing things’

      Some people are all in favor of cables, but for me that is not really a choice as I cannot/dont want to run cables. I have some where it was easy, but I mostly rely on the ESP8266.

      I currently do have a circuit (bare ESP-12F) and a program for BME280 in deepsleep… just waiting for the BME.
      I know you are quite capable to write your own routine, but I would be happy to send you mine if u want, just let me know

  2. As the Dutch saying goes: I am rather lazy than tired, so yes please, appreciated.

    I am in the same boat as you are, or to put it more precisely, my BME is!

  3. ….Presuming you saved the program as “”, that is the name you need to us…..

    I assume it shall be “” as is later used in “./ ‘cupboard/temperature1’ ‘cupboard/humidity1’ 4”

    If I follow the instructions, I get the following problem, do you know why?
    pi@raspberrypi:~/Documents/Humidity $ ./ ‘cupboard/temperature1’ ‘cupboard/humidity1’ 23
    bash: ./ Permission denied

    Thank you.

    1. Vlad. On the name you are right. My bad. With regard to the permission denied…….did you set the permissions? (I presume not). Set the file to an executable with chmod. I always use 777 to set max permission but many use 755

      1. Thanks a lot! This problem is solved, however I got this answer: -(

        By any chance, do you know what the problem can be?

        pi@raspberrypi:~ $ sudo ./ ‘cupboard/temperature1’ ‘cupboard/humidity1’ 23
        Mosquitto Temp MSG cupboard/temperature1
        Mosquitto Humidity MSG cupboard/humidity1
        Mosquitto LWT MSG cupboard/LWT
        Args length: 4
        Logging sensor measurements to MQTT every 300 seconds.
        Press Ctrl-C to quit.
        Connecting to MQTT on servername
        Traceback (most recent call last):
        File “./”, line 78, in
        mqttc.connect(MOSQUITTO_HOST,MOSQUITTO_PORT, keepalive=FREQUENCY_SECONDS+10)
        File “/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.5.1-py2.7.egg/paho/mqtt/”, line 941, in connect
        return self.reconnect()
        File “/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.5.1-py2.7.egg/paho/mqtt/”, line 1075, in reconnect
        sock = self._create_socket_connection()
        File “/usr/local/lib/python2.7/dist-packages/paho_mqtt-1.5.1-py2.7.egg/paho/mqtt/”, line 3546, in _create_socket_connection
        return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
        File “/usr/lib/python2.7/”, line 557, in create_connection
        for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        socket.gaierror: [Errno -2] Name or service not known

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: