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
5import board
6import adafruit_dht
7
8# Initial the dht device, with data pin connected to:
9dhtDevice = adafruit_dht.DHT22(board.D18)
10
11# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio.
12# This may be necessary on a Linux single board computer like the Raspberry Pi,
13# but it will not work in CircuitPython.
14# dhtDevice = adafruit_dht.DHT22(board.D18, use_pulseio=False)
15
16while True:
17 try:
18 # Print the values to the serial port
19 temperature_c = dhtDevice.temperature
20 temperature_f = temperature_c * (9 / 5) + 32
21 humidity = dhtDevice.humidity
22 print(
23 "Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
24 temperature_f, temperature_c, humidity
25 )
26 )
27
28 except RuntimeError as error:
29 # Errors happen fairly often, DHT's are hard to read, just keep going
30 print(error.args[0])
31 time.sleep(2.0)
32 continue
33 except Exception as error:
34 dhtDevice.exit()
35 raise error
36
37 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# import for dht devices and 7-segment display devices
10import time
11from board import D2, TX, RX, D1
12import busio
13import digitalio
14from adafruit_max7219 import bcddigits
15import adafruit_dht
16
17
18clk = RX
19din = TX
20cs = digitalio.DigitalInOut(D1)
21spi = busio.SPI(clk, MOSI=din)
22display = bcddigits.BCDDigits(spi, cs, nDigits=8)
23display.brightness(5)
24
25# initial the dht device
26dhtDevice = adafruit_dht.DHT22(D2)
27
28while True:
29 try:
30 # show the values to the serial port
31 temperature = dhtDevice.temperature * (9 / 5) + 32
32 humidity = dhtDevice.humidity
33 # print("Temp: {:.1f} F Humidity: {}% ".format(temperature, humidity))
34
35 # now show the values on the 8 digit 7-segment display
36 display.clear_all()
37 display.show_str(0, "{:5.1f}{:5.1f}".format(temperature, humidity))
38 display.show()
39
40 except RuntimeError as error:
41 print(error.args[0])
42
43 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 # pylint: disable=protected-access
55 dhtDevice._trig_wait = milliseconds
56
57 # pylint: disable=protected-access
58 print(f"Using 'trig_wait' of {dhtDevice._trig_wait}")
59 # Reset the read count for next loop
60 reads_count = 0
61
62 # Create the key on the reads dictionary with the milliseconds used on
63 # this try.
64 if milliseconds not in reads:
65 reads[milliseconds] = {"total_reads": 0}
66
67 for try_number in range(0, max_retries_per_time):
68 try:
69 # Read temperature and humidity
70 temperature = dhtDevice.temperature
71 humidity = dhtDevice.humidity
72 read_values = {"temperature": temperature, "humidity": humidity}
73
74 if try_number not in reads[milliseconds]:
75 reads[milliseconds][try_number] = read_values
76
77 reads_count += 1
78 except RuntimeError as e:
79 time.sleep(2)
80 else:
81 time.sleep(1)
82
83 reads[milliseconds]["total_reads"] = reads_count
84
85 print(f"Total read(s): {reads[milliseconds]['total_reads']}\n")
86 dhtDevice.exit()
87
88# Gather the highest read numbers from all reads done.
89best_result = max(
90 reads[milliseconds]["total_reads"]
91 for milliseconds in reads # pylint: disable=consider-using-dict-items
92)
93# Gather best time(s) in milliseconds where we got more reads
94best_times = [
95 milliseconds
96 for milliseconds in reads # pylint: disable=consider-using-dict-items
97 if reads[milliseconds]["total_reads"] == best_result
98]
99print(
100 f"Maximum reads: {best_result} out of {max_retries_per_time} with the "
101 f"following times: {', '.join([str(t) for t in best_times])}"
102)
103
104# change the value on the line below to see all reads performed.
105print_all = False
106if print_all:
107 print(json.dumps(reads))