DHT11/DHT22 with Raspberry Pi

try changing the code to the below to get some output

while True:
    try:
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 27) #11 is the sensor type, 27 is the GPIO pin number
        print "Humidity: " + str(humidity11) + " Temperature: " + str(temp11)

Okey,
I purchased the original sensor DHT11 from the Adafruit and again the result is the same. It seems that the problem is not in the sensor.

I try to post a video:

See how the values are changing from real to unreal…

How is your DHT11 wired, can you take a picture or draw up a schematic?

Hello Adam,

VCC is to 5 volts
GND is to ground
DATA is to GPIO 17 as also I try to 27 (next one) and the result is the same.

I thought it was because of the pull up resistor, but no…the same results…

Can you take a picture of your wiring so I can look it over?

Yes.
Here is the picture.
Red wire is power - connected to 5 volts
Yellow wire is data - connected to p18 (gpio 18)
White wire is gnd - connected to ground.

I also use a pullup resistor - 10K. Tried with 4.7 but the results are the same.

Second picture is showing the wrong value. It is not all the time but on some kind of measurements.

Another problem is that the script is stop working and I loose connection after some time of working - 4-5 hours.

I try to impelent the code to take readings in every 5 minutes as taking the current minute from date function. Here is the complete code:

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

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

mqttc = mqtt.Client(client_id="79b46ab0-fa0b-11e6-960c-5f3000377163")
mqttc.username_pw_set("805dbad0-a6d5-11e6-a85d-c165103f15c2", password="0057f5f6af5b1d9d88d3b409beffd26802a16c45")
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)

topic_dht11_temp = "v1/805dbad0-a6d5-11e6-a85d-c165103f15c2/things/79b46ab0-fa0b-11e6-960c-5f3000377163/data/1"
topic_dht11_humidity = "v1/805dbad0-a6d5-11e6-a85d-c165103f15c2/things/79b46ab0-fa0b-11e6-960c-5f3000377163/data/2"
#topic_dht22_temp = "v1/805dbad0-a6d5-11e6-a85d-c165103f15c2/things/c81bf3e0-dc23-11e6-ae8c-f90e83be502a/data/3"
#topic_dht22_humidity = "v1/805dbad0-a6d5-11e6-a85d-c165103f15c2/things/c81bf3e0-dc23-11e6-ae8c-f90e83be502a/data/4"

t = datetime.datetime.now()
minute = t.minute
if(minute%5 ==0):
    while True:
        try:
            humidity11, temp11 = Adafruit_DHT.read_retry(11, 18) #11 is the sensor type, 17 is the GPIO pin number
            #humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO 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()

Did anybody get a stable version of the code?

I still have problems with working a couple of hours and then it shows that the device is offline. Tried with cronjob and manual start and it is the same!

Some possible issues that could cause the device to go offline:

  1. mqttc.loop() should be called to process mqtt messages inside the main loop to keep the connection alive.
while True:
    try:
        mqttc.loop()
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number
  1. Perhaps the connection is getting cut at some point due to network issues, or issues with the Adafruit_DHT.read_retry taking too long and preventing the client from sending a keepalive packet to the server within the 60 second interval specified. To fix this you could try checking for disconnect using the on_disconnect handler in the mqtt client and reconnecting.
import paho.mqtt.client as mqtt
import time
import sys
import Adafruit_DHT

USERNAME = "username"
PASSWORD = "password"
CLIENT_ID = "client_id"

# The callback for when the client disconnects from the server.
def on_connect(client, cayenne, rc):
    print("Connected with result code "+str(rc))

# The callback for when the client disconnects from the server.
def on_disconnect(client, userdata, rc):
    print("Disconnected with result code "+str(rc))
    reconnected = False
    while not reconnected:
        try:
            client.reconnect()
            reconnected = True
        except:
            print("Reconnect failed, retrying")
            time.sleep(5)

time.sleep(30) #Sleep to allow wireless to connect before starting MQTT
mqttc = mqtt.Client(CLIENT_ID)
mqttc.username_pw_set(USERNAME, password=PASSWORD)
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)

topic_dht11_temp = "v1/{}/things/{}/data/1".format(USERNAME, CLIENT_ID)
topic_dht11_humidity = "v1/{}/things/{}/data/2".format(USERNAME, CLIENT_ID)
topic_dht22_temp = "v1/{}/things/{}/data/3".format(USERNAME, CLIENT_ID)
topic_dht22_humidity = "v1/{}/things/{}/data/4".format(USERNAME, CLIENT_ID)

while True:
    try:
        mqttc.loop()
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO 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()

Alternatively, rather than using paho.mqtt directly you could use the cayenne-mqtt Python module which wraps the paho.mqtt module to make is easier to use. That’s available via pip: cayenne-mqtt · PyPI. Use pip install cayenne-mqtt to install.

An example script using cayenne-mqtt with DHT is below, but it hasn’t been tested with DHT sensors.

#!/usr/bin/env python
import cayenne.client as cayenne
import time
import Adafruit_DHT

# Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
MQTT_USERNAME  = "username"
MQTT_PASSWORD  = "password"
MQTT_CLIENT_ID = "client_id"

client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

timestamp = 0

while True:
    client.loop()
    
    if (time.time() > timestamp + 5):
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number

        if temp11 is not None:
            client.virtualWrite(1, temp11, cayenne.TYPE_TEMPERATURE, cayenne.UNIT_CELSIUS)
        if humidity11 is not None:
           client.virtualWrite(2, humidity11, cayenne.TYPE_RELATIVE_HUMIDITY, cayenne.UNIT_PERCENT)
        if temp22 is not None:
            client.virtualWrite(3, temp22, cayenne.TYPE_TEMPERATURE, cayenne.UNIT_CELSIUS)
        if humidity22 is not None:
            client.virtualWrite(4, humidity22, cayenne.TYPE_RELATIVE_HUMIDITY, cayenne.UNIT_PERCENT)
        timestamp = time.time()
3 Likes

I thought for sure I had loop() in my code…might have been something I added and forgot to update my post. I’ll check tonight to see. If that doesn’t make a difference I’ll give the Cayenne library a try.

I will also make tests with all the different approaches that @jburhenn presents. I will keep you up to date for the results.

thank you !

Hello Everybody,
Thanks to @jburhenn I can confirm that more than 10 HOURS the DHT11 sensor is working WITHOUT going in offline mode.
I use the following code:

import cayenne.client as cayenne
import time
import Adafruit_DHT


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

MQTT_USERNAME  = "YOUR_USERNAME"
MQTT_PASSWORD  = "YOUR_PASSWORD"
MQTT_CLIENT_ID = "YOUR_CLIENDID"

client = cayenne.CayenneMQTTClient()
client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID)

timestamp = 0

while True:
    client.loop()
    if (time.time() > timestamp + 5):
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 18) #11 is the sensor type, 18 is the GPIO pin number that DATA wire is connected to


        if temp11 is not None:
            client.virtualWrite(1, temp11, cayenne.TYPE_TEMPERATURE, cayenne.UNIT_CELSIUS)
        if humidity11 is not None:
           client.virtualWrite(2, humidity11, cayenne.TYPE_RELATIVE_HUMIDITY, cayenne.UNIT_PERCENT)
        timestamp = time.time()

However I still have problems with the sensor PEAKS as you can see in the picture from the graph below:

I think that these peaks might be from the wire that I use or the sensor ( I change it with orignal one from Adafruit). I use 1.5 meter long 4 wire cable for alarms installation.

3 Likes

Glad to hear it appears to work for you. As for the peaks you get you may want to just try discarding any data points that seem bad, In other words, you could just skip sending humidity data if it is greater than 100%. Of course, that may not work if you get peak values that are less than 100%.

It is a good idea. I think that these DHT11 sensors are not so reliable. In compare with SHT10, the temperature is the same, but humidity values are differ with 10%. In Monday I will have original DHT22. I will try also with it. Compare the data with my Silicon Labs SENSOR-PUCK Kit, the data is similar to the data from the SHT10 sensor.

if i get some sparetime on the weekend i will try your code with my DHT22
Thx in advance…

You have to modify it a little bit! Be careful for the GPIO number and sensor type number :slight_smile:

Yeah…
I just realised that you removed the codelines for the DHT22.
Thats unfortunate, because i don`t have the time (This weekend) to rewrite the code…

I will post you the lines for DHT22 later. I am on road right now. Sorry!
In Monday I also will have DHT22 sensor. I want to compare the measurements
with DHT11 and SHT10 sensor.