3

There are more than 100 questions on this site concerning DHT11 or DHT22 sensors and I have used these with Python and c code using various libraries.

None that I have tried seem to give reliable consistent results.

I have been using the Adafruit code for some time on a Pi3B+ to publish temperature/humidity to MQTT but this seemed wasteful, so I decided to utilise a PiB+ which could be left running.

Despite using a cloned card it failed to work; reinstalling the Adafruit code did not seem to help. There seemed nothing wrong with the sensor as my c code still performed perfectly.

2 Answers 2

3

While searching I came across some of Joan's code (which has been recently published or updated) - this seemed to fit the bill (even though it looked too simple). There is none of the arcane installation Adafruit required and it seems to work every time without missing readings due to timing errors.

All that is needed is a simple python module and pigpiod - which is included in Raspbian.

I wrote the following wrapper around this module:-

#!/usr/bin/env python3
# Program to read current temperature and humidity and post single message to MQTT BROKER

"""
    A Program to read the DHTXX temperature/humidity sensors.
    Post single message to MQTT BROKER

    REQUIREMENTS
    DHT.py    download "module" from http://abyz.me.uk/rpi/pigpio/code/DHT.py
    pigpiod running

    apt-get install -y mosquitto mosquitto-clients
    sudo pip3 install paho-mqtt
"""

import paho.mqtt.publish as publish
import json

BROKER = 'localhost'

sensor_data = {'date': 0, 'temperature': 0, 'humidity': 0}
topicPrefix = "weather"

import sys
import pigpio
import DHT
import time
import datetime

# Sensor should be set to DHT.DHT11, DHT.DHTXX or DHT.DHTAUTO
sensor = DHT.DHT11

pin = 4     # Data - Pin 7 (BCM 4)

def output_data(timestamp, temperature, humidity):
    # Sample output Date: 2019-11-17T10:55:08, Temperature: 25°C, Humidity: 72%
    date = datetime.datetime.fromtimestamp(timestamp).replace(microsecond=0).isoformat()
#     print(u"Date: {:s}, Temperature: {:g}\u00b0C, Humidity: {:g}%".format(date, temperature, humidity))
    sensor_data['temperature'] = temperature
    sensor_data['humidity'] = humidity
    sensor_data['date'] = date
    publish.single(topicPrefix, payload=json.dumps(sensor_data), qos=1, retain=True, hostname=BROKER,
        port=1883, client_id="RaspberryPi", keepalive=60)



pi = pigpio.pi()
if not pi.connected:
  exit()

s = DHT.sensor(pi, pin, model = sensor)

tries = 5   # try 5 times if error
while tries:
    try:
        timestamp, gpio, status, temperature, humidity = s.read()   #read DHT device
        if(status == DHT.DHT_TIMEOUT):  # no response from sensor
            exit()
        if(status == DHT.DHT_GOOD):
            output_data(timestamp, temperature, humidity)
            exit()      # Exit after successful read
        time.sleep(2)
        tries -=1
    except KeyboardInterrupt:
        break

This code is intended to run from crontab
NOTE Unless DHT.py is in the same directory it should be in a directory on the PYTHONPATH

The following is an extract from my crontab.

PYTHONPATH=/home/pi/bin/python
# This will publish into Broker on localhost
# Should Publish nothing if sensor missing
1,16,31,46 * * * * /home/pi/mqtt-dht11s.py
1
  • 2
    The DHT11 should be rock solid. A DHT22 may lock up occasionally, perhaps after a day, perhaps after 3 months. That is nothing to do with the software (it happens whatever the software and on other platforms such as the Arduino). If a DHT22 locks up the only solution I have found is to power cycle the device.
    – joan
    Commented Nov 17, 2019 at 9:39
3

The following is simplified code which prints a single reading.

Unless DHT.py is in the same directory it should be in a directory on the PYTHONPATH

#!/usr/bin/env python3

# 2020-09-27
"""
    A Program to read the DHTXX temperature/humidity sensors.

    REQUIREMENTS
    DHT.py    download "module" from http://abyz.me.uk/rpi/pigpio/code/DHT.py
    pigpiod running
"""

import sys
import pigpio
import DHT
import time
import datetime

# Sensor should be set to DHT.DHT11, DHT.DHTXX or DHT.DHTAUTO
sensor = DHT.DHT11

pin = 4     # Data - Pin 7 (BCM 4)

def output_data(timestamp, temperature, humidity):
    # Sample output Date: 2019-11-17T10:55:08, Temperature: 25°C, Humidity: 72%
    date = datetime.datetime.fromtimestamp(timestamp).replace(microsecond=0).isoformat()
    print(u"Date: {:s}, Temperature: {:g}\u00b0C, Humidity: {:g}%".format(date, temperature, humidity))

pi = pigpio.pi()
if not pi.connected:
  exit()

s = DHT.sensor(pi, pin, model = sensor)

tries = 5   # try 5 times if error
while tries:
    try:
        timestamp, gpio, status, temperature, humidity = s.read()   #read DHT device
        if(status == DHT.DHT_TIMEOUT):  # no response from sensor
            exit()
        if(status == DHT.DHT_GOOD):
            output_data(timestamp, temperature, humidity)
            exit()      # Exit after successful read
        time.sleep(2)
        tries -=1
    except KeyboardInterrupt:
        break

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.