Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4801

Python • Re: Raspberry pi 5 with DHT11

$
0
0
First install the dtoverlay driver in linux

Connect DHT11 VCC to 3.3V
Connect DHT11 GND to GND
Connect DHT11 DAT pin to an unused GPIO PIN.

On my example I choose GPIO21

Now install the DTOVERLAY DHT11

type sudo nano /boot/firmware/config.txt
Just after the [ALL] add this line

Code:

[all]dtoverlay=dht11,gpiopin=21
CTRL-x and yes to save

Reboot

Now you should see the DHT11 sensor appears "/sys/bus/iio/devices" folder

Code:

daniel@Pi5:~ $ cd /sys/bus/iio/devicesdaniel@Pi5:/sys/bus/iio/devices $ lsiio:device0daniel@Pi5:/sys/bus/iio/devices $ cd iio:device0daniel@Pi5:/sys/bus/iio/devices/iio:device0 $ lsin_humidityrelative_input  name     power      ueventin_temp_input              of_node  subsystem  waiting_for_supplierdaniel@Pi5:/sys/bus/iio/devices/iio:device0 $ cat in_humidityrelative_input 36000daniel@Pi5:/sys/bus/iio/devices/iio:device0 $ cat in_temp_input 20000daniel@Pi5:/sys/bus/iio/devices/iio:device0 $ 
if iio:device0 exist then you sensor works!

And this is a small script to access the DHT11 via python

Code:

#!/bin/python3import timedevice0 = "/sys/bus/iio/devices/iio:device0"#function to read first line and return integerdef readFirstLine(filename):    try:        f = open(filename,"rt")        value =  int(f.readline())        f.close()        return True, value    except ValueError:        f.close()        return False,-1    except OSError:        return False,0try:    while True:        Flag, Temperature = readFirstLine(device0+"/in_temp_input")        print("Temperature:",end="")        if Flag:            print(Temperature // 1000,"\u2103",end="\t")        else:            print("N.A.",end="\t")        Flag, Humidity = readFirstLine(device0+"/in_humidityrelative_input")        print("Humidity:",end="")        if Flag:            print(Humidity // 1000,"%")        else:            print("N.A.")        time.sleep(2.0)except KeyboardInterrupt:    pass
The result

Code:

daniel@Pi5:~ $ python readDHT11.pyTemperature:27 ℃Humidity:31 %Temperature:26 ℃Humidity:32 %Temperature:26 ℃Humidity:32 %Temperature:26 ℃Humidity:32 %Temperature:26 ℃Humidity:32 %Temperature:26 ℃Humidity:32 %^Cdaniel@Pi5:~ $ 

Statistics: Posted by danjperron — Sat Feb 24, 2024 6:35 pm



Viewing all articles
Browse latest Browse all 4801

Trending Articles