How can I interface a DHT11 module with a PYNQ-Z1 board to read temperature and humidity data?
I tried this. `from pynq import GPIO
from pynq.overlays.base import BaseOverlay
import time
Main execution
base = BaseOverlay(“base.bit”)
Create GPIO object for the DHT11 data pin, initially as output
dht11_pin = GPIO(GPIO.get_gpio_pin(3), ‘out’) # Use pin 1
while True:
try:
print(“Starting data transmission…”)
# Start data transmission
dht11_pin.write(0) # Pull down pin for at least 18ms
time.sleep(0.018) # 18ms
# Pull up and wait for response
dht11_pin.write(1) # Pull up
time.sleep(0.000040) # 40us
# Switch to input mode
dht11_pin.release() # Release the GPIO
dht11_pin = GPIO(GPIO.get_gpio_pin(3), 'in') # Reinitialize as input
print("Waiting for sensor response...")
while dht11_pin.read() == 1:
continue
print("Sensor response detected.")
# Sensor's low signal response
print("Waiting for sensor's low signal response...")
while dht11_pin.read() == 0:
continue
print("Sensor's low signal response detected.")
# Sensor's high signal response
print("Waiting for sensor's high signal response...")
while dht11_pin.read() == 1:
continue
print("Sensor's high signal response detected.")
# Read 40 bits of data
data = []
print("Reading data bits...")
for _ in range(40):
while dht11_pin.read() == 0:
continue
# Measure high pulse duration
start = time.time()
while dht11_pin.read() == 1:
continue
duration = time.time() - start
# Decode bit (>50us is 1, <50us is 0)
data.append(1 if duration > 0.000050 else 0)
print("Data bits read successfully.")
# Convert bits to bytes
humidity_int = int(''.join(map(str, data[0:8])), 2)
humidity_dec = int(''.join(map(str, data[8:16])), 2)
temp_int = int(''.join(map(str, data[16:24])), 2)
temp_dec = int(''.join(map(str, data[24:32])), 2)
checksum = int(''.join(map(str, data[32:40])), 2)
# Verify checksum
if (humidity_int + humidity_dec + temp_int + temp_dec) & 0xFF == checksum:
print(f"Temperature: {temp_int + (temp_dec / 10.0)}°C, Humidity: {humidity_int + (humidity_dec / 10.0)}%")
else:
print("Failed to read sensor data: Checksum mismatch")
except Exception as e:
print(f"Error occurred: {e}")
time.sleep(2) # Wait before the next read` there is no output