Untitled

 avatar
unknown
plain_text
6 months ago
2.2 kB
3
Indexable
import pigpio
import time

DHT_PIN = 17

class DHT22:
    def __init__(self, pi, gpio):
        self.pi = pi
        self.gpio = gpio
        self.high_tick = 0
        self.bit = 40
        self.temperature = 0
        self.humidity = 0
        self.either_edge_cb = None
        self.pi.set_mode(gpio, pigpio.INPUT)
        self.pi.set_pull_up_down(gpio, pigpio.PUD_OFF)
        self.either_edge_cb = self.pi.callback(gpio, pigpio.EITHER_EDGE, self._cb)

    def _cb(self, gpio, level, tick):
        if level == 0:
            if self.high_tick != 0:
                t = pigpio.tickDiff(self.high_tick, tick)
                if 50 <= t <= 80:
                    self.bit = 40
                    self.temperature = 0
                    self.humidity = 0
                elif t < 180:
                    self.bit -= 1
                    if self.bit >= 32:
                        self.humidity = (self.humidity << 1) + (1 if t > 100 else 0)
                    elif 16 <= self.bit < 32:
                        self.temperature = (self.temperature << 1) + (1 if t > 100 else 0)
        else:
            self.high_tick = tick

    def read(self):
        self.pi.write(self.gpio, 0)
        time.sleep(0.017)
        self.pi.set_mode(self.gpio, pigpio.INPUT)
        time.sleep(0.2)
        return self.humidity / 10.0, self.temperature / 10.0

pi = pigpio.pi()
if not pi.connected:
    print("Failed to connect to pigpio daemon")
    exit()

dht22 = DHT22(pi, DHT_PIN)

print("DHT22 Test Script using pigpio")
print(f"Using GPIO pin: {DHT_PIN}")
print("Press CTRL+C to exit")
print("Reading sensor data...")

try:
    while True:
        humidity, temperature = dht22.read()
        if humidity != 0 and temperature != 0:
            print(f"Temperature: {temperature:.1f}°C")
            print(f"Humidity: {humidity:.1f}%")
        else:
            print("Failed to retrieve data from the sensor")
        print("--------------------")
        time.sleep(3)

except KeyboardInterrupt:
    print("Script terminated by user")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    pi.stop()
Editor is loading...
Leave a Comment