Simple test

Ensure your device works with this simple test.

examples/dht_simpletest.py
 1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
 2# SPDX-License-Identifier: MIT
 3
 4import time
 5
 6import board
 7
 8import adafruit_dht
 9
10# Initial the dht device, with data pin connected to:
11dhtDevice = adafruit_dht.DHT22(board.D18)
12
13# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio.
14# This may be necessary on a Linux single board computer like the Raspberry Pi,
15# but it will not work in CircuitPython.
16# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False)
17
18while True:
19    try:
20        # Print the values to the serial port
21        temperature_c = dhtDevice.temperature
22        temperature_f = temperature_c * (9 / 5) + 32
23        humidity = dhtDevice.humidity
24        print(f"Temp: {temperature_f:.1f} F / {temperature_c:.1f} C    Humidity: {humidity}% ")
25
26    except RuntimeError as error:
27        # Errors happen fairly often, DHT's are hard to read, just keep going
28        print(error.args[0])
29        time.sleep(2.0)
30        continue
31    except Exception as error:
32        dhtDevice.exit()
33        raise error
34
35    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# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
 2# SPDX-License-Identifier: MIT
 3
 4"""
 5example of reading temperature and humidity from a DHT device
 6and displaying results to the serial port and a 8 digit 7-segment display
 7the DHT device data wire is connected to board.D2
 8"""
 9
10# import for dht devices and 7-segment display devices
11import time
12
13import busio
14import digitalio
15from adafruit_max7219 import bcddigits
16from board import D1, D2, RX, TX
17
18import adafruit_dht
19
20clk = RX
21din = TX
22cs = digitalio.DigitalInOut(D1)
23spi = busio.SPI(clk, MOSI=din)
24display = bcddigits.BCDDigits(spi, cs, nDigits=8)
25display.brightness(5)
26
27# initial the dht device
28dhtDevice = adafruit_dht.DHT22(D2)
29
30while True:
31    try:
32        # show the values to the serial port
33        temperature = dhtDevice.temperature * (9 / 5) + 32
34        humidity = dhtDevice.humidity
35        # print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity))
36
37        # now show the values on the 8 digit 7-segment display
38        display.clear_all()
39        display.show_str(0, f"{temperature:5.1f}{humidity:5.1f}")
40        display.show()
41
42    except RuntimeError as error:
43        print(error.args[0])
44
45    time.sleep(2.0)

Time calibration advance test

Example to identify best waiting time for the sensor

examples/dht_time_calibration_advance.py
  1# SPDX-FileCopyrightText: 2021 yeyeto2788 for Adafruit Industries
  2# SPDX-License-Identifier: MIT
  3
  4"""
  5This script let's you check the best timing for you sensor as other people have face timing issues
  6as seen on issue https://github.com/adafruit/Adafruit_CircuitPython_DHT/issues/66.
  7
  8By changing the variables values below you will be able to check the best timing for you sensor,
  9take into account that by most datasheets the timing for the sensor are 0.001 DHT22 and
 100.018 for DHT11 which are the default values of the library.
 11"""
 12
 13import json
 14import time
 15
 16import board
 17
 18import adafruit_dht
 19
 20# Change the pin used below
 21pin_to_use = "PG6"
 22
 23# Maximum number of tries per timing
 24max_retries_per_time = 10
 25# Minimum wait time from where to start testing
 26min_time = 1500
 27# Maximum wait time on where to stop testing
 28max_time = 2000
 29# Increment on time
 30time_increment = 100
 31
 32# Variable to store all reads on a try
 33reads = {}
 34
 35initial_msg = f"""
 36\nInitializing test with the following parameters:
 37
 38- Maximum retries per waiting time: {max_retries_per_time}
 39- Start time (ms): {min_time}
 40- End time (ms): {max_time}
 41- Increment time (ms): {time_increment}
 42
 43This execution will try to read the sensor {max_retries_per_time} times
 44for {len(range(min_time, max_time, time_increment))} different wait times values.
 45
 46"""
 47# Print initial message on the console.
 48print(initial_msg)
 49
 50for milliseconds in range(min_time, max_time, time_increment):
 51    # Instantiate the DHT11 object.
 52    dhtDevice = adafruit_dht.DHT11(pin=getattr(board, pin_to_use))
 53    # Change the default wait time for triggering the read.
 54    dhtDevice._trig_wait = milliseconds
 55
 56    print(f"Using 'trig_wait' of {dhtDevice._trig_wait}")
 57    # Reset the read count for next loop
 58    reads_count = 0
 59
 60    # Create the key on the reads dictionary with the milliseconds used on
 61    # this try.
 62    if milliseconds not in reads:
 63        reads[milliseconds] = {"total_reads": 0}
 64
 65    for try_number in range(0, max_retries_per_time):
 66        try:
 67            # Read temperature and humidity
 68            temperature = dhtDevice.temperature
 69            humidity = dhtDevice.humidity
 70            read_values = {"temperature": temperature, "humidity": humidity}
 71
 72            if try_number not in reads[milliseconds]:
 73                reads[milliseconds][try_number] = read_values
 74
 75            reads_count += 1
 76        except RuntimeError:
 77            time.sleep(2)
 78        else:
 79            time.sleep(1)
 80
 81    reads[milliseconds]["total_reads"] = reads_count
 82
 83    print(f"Total read(s): {reads[milliseconds]['total_reads']}\n")
 84    dhtDevice.exit()
 85
 86# Gather the highest read numbers from all reads done.
 87best_result = max(reads[milliseconds]["total_reads"] for milliseconds in reads)
 88# Gather best time(s) in milliseconds where we got more reads
 89best_times = [
 90    milliseconds for milliseconds in reads if reads[milliseconds]["total_reads"] == best_result
 91]
 92print(
 93    f"Maximum reads: {best_result}  out of {max_retries_per_time} with the "
 94    f"following times: {', '.join([str(t) for t in best_times])}"
 95)
 96
 97# change the value on the line below to see all reads performed.
 98print_all = False
 99if print_all:
100    print(json.dumps(reads))