Simple test

Ensure your device works with this simple test.

examples/dht_simpletest.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import board
import adafruit_dht

# Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT22(board.D18)

# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio.
# This may be necessary on a Linux single board computer like the Raspberry Pi,
# but it will not work in CircuitPython.
# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False)

while True:
    try:
        # Print the values to the serial port
        temperature_c = dhtDevice.temperature
        temperature_f = temperature_c * (9 / 5) + 32
        humidity = dhtDevice.humidity
        print(
            "Temp: {:.1f} F / {:.1f} C    Humidity: {}% ".format(
                temperature_f, temperature_c, humidity
            )
        )

    except RuntimeError as error:
        # Errors happen fairly often, DHT's are hard to read, just keep going
        print(error.args[0])
        time.sleep(2.0)
        continue
    except Exception as error:
        dhtDevice.exit()
        raise error

    time.sleep(2.0)

DHT to Led Display

Example of reading temperature and humidity from a DHT device and displaying results to the serial port and a 8 digit 7-segment display

examples/dht_to_led_display.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
example of reading temperature and humidity from a DHT device
and displaying results to the serial port and a 8 digit 7-segment display
the DHT device data wire is connected to board.D2
"""
# import for dht devices and 7-segment display devices
import time
from board import D2, TX, RX, D1
import busio
import digitalio
from adafruit_max7219 import bcddigits
import adafruit_dht


clk = RX
din = TX
cs = digitalio.DigitalInOut(D1)
spi = busio.SPI(clk, MOSI=din)
display = bcddigits.BCDDigits(spi, cs, nDigits=8)
display.brightness(5)

# initial the dht device
dhtDevice = adafruit_dht.DHT22(D2)

while True:
    try:
        # show the values to the serial port
        temperature = dhtDevice.temperature * (9 / 5) + 32
        humidity = dhtDevice.humidity
        # print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity))

        # now show the values on the 8 digit 7-segment display
        display.clear_all()
        display.show_str(0, "{:5.1f}{:5.1f}".format(temperature, humidity))
        display.show()

    except RuntimeError as error:
        print(error.args[0])

    time.sleep(2.0)

Time calibration advance test

Example to identify best waiting time for the sensor

examples/dht_time_calibration_advance.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
# SPDX-FileCopyrightText: 2021 yeyeto2788 for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
This script let's you check the best timing for you sensor as other people have face timing issues
as seen on issue https://github.com/adafruit/Adafruit_CircuitPython_DHT/issues/66.

By changing the variables values below you will be able to check the best timing for you sensor,
take into account that by most datasheets the timing for the sensor are 0.001 DHT22 and
0.018 for DHT11 which are the default values of the library.
"""

import json
import time

import board

import adafruit_dht

# Change the pin used below
pin_to_use = "PG6"

# Maximum number of tries per timing
max_retries_per_time = 10
# Minimum wait time from where to start testing
min_time = 1500
# Maximum wait time on where to stop testing
max_time = 2000
# Increment on time
time_increment = 100

# Variable to store all reads on a try
reads = {}

initial_msg = f"""
\nInitializing test with the following parameters:

- Maximum retries per waiting time: {max_retries_per_time}
- Start time (ms): {min_time}
- End time (ms): {max_time}
- Increment time (ms): {time_increment}

This execution will try to read the sensor {max_retries_per_time} times
for {len(range(min_time, max_time, time_increment))} different wait times values.

"""
# Print initial message on the console.
print(initial_msg)

for milliseconds in range(min_time, max_time, time_increment):
    # Instantiate the DHT11 object.
    dhtDevice = adafruit_dht.DHT11(pin=getattr(board, pin_to_use))
    # Change the default wait time for triggering the read.
    # pylint: disable=protected-access
    dhtDevice._trig_wait = milliseconds

    # pylint: disable=protected-access
    print(f"Using 'trig_wait' of {dhtDevice._trig_wait}")
    # Reset the read count for next loop
    reads_count = 0

    # Create the key on the reads dictionary with the milliseconds used on
    # this try.
    if milliseconds not in reads:
        reads[milliseconds] = {"total_reads": 0}

    for try_number in range(0, max_retries_per_time):
        try:
            # Read temperature and humidity
            temperature = dhtDevice.temperature
            humidity = dhtDevice.humidity
            read_values = {"temperature": temperature, "humidity": humidity}

            if try_number not in reads[milliseconds]:
                reads[milliseconds][try_number] = read_values

            reads_count += 1
        except RuntimeError as e:
            time.sleep(2)
        else:
            time.sleep(1)

    reads[milliseconds]["total_reads"] = reads_count

    print(f"Total read(s): {reads[milliseconds]['total_reads']}\n")
    dhtDevice.exit()

# Gather the highest read numbers from all reads done.
best_result = max([reads[milliseconds]["total_reads"] for milliseconds in reads])

# Gather best time(s) in milliseconds where we got more reads
best_times = [
    milliseconds
    for milliseconds in reads
    if reads[milliseconds]["total_reads"] == best_result
]
print(
    f"Maximum reads: {best_result}  out of {max_retries_per_time} with the "
    f"following times: {', '.join([str(t) for t in best_times])}"
)

# change the value on the line below to see all reads performed.
print_all = False
if print_all:
    print(json.dumps(reads))