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 https://github.com/eclipse/paho.mqtt.python.git => download the client
cd paho.mqtt.python => go to proper directory
python setup.py 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 https://github.com/adafruit/Adafruit_Python_DHT.git => 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 setup.py 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

do:
cd examples
sudo ./AdafruitDHT.py 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
into
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 “mqtt.dht.sensor.py”, that is the name you need to use instead of “mqtt.channel.py” (the name mentioned in the “Usage”).
also.
I started my program as follows:

./mqtt.dhtsensor.py '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 “dht.sh” that contained the single line:
./mqtt.dhtsensor.py '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 dht.sh 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:
Error
-bash: git: command not found
Solution
sudo apt-get install git
Error
File “setup.py”, line 5, in
from setuptools import setup, find_packages
ImportError: No module named setuptools
Solution
sudo apt-get install python-setuptools
Error
no module named requests
Solution
sudo pip install requests
Error
No pip
Solution
apt install python-pip #python 2
Error
Append error, logging in again: [Errno -2] Name or service not known
Solution
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 mqtt.dhtsensor.py 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.

Error
“no module named Adafruit_DHT”
Solution
Go to the Adafruit_Python_DHT folder and do:
sudo python setup.py 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

Advertisements

4 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!

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s

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