Skip to content
김선영 edited this page Oct 15, 2024 · 5 revisions
import time
import json
import gpiod
import sys

DHT_PIN = 4 

def read_dht11_sensor():
    chip = gpiod.Chip('gpiochip0')
    
    try:
        line = chip.get_line(DHT_PIN)
        line.request(consumer="DHT11", type=gpiod.LINE_REQ_DIR_OUT)
        
        line.set_value(1)
        time.sleep(0.025)
        line.set_value(0)
        time.sleep(0.02)
        
        line.release()
        line.request(consumer="DHT11", type=gpiod.LINE_REQ_DIR_IN, flags=gpiod.LINE_REQ_FLAG_BIAS_PULL_UP)
        
        data = []
        for _ in range(40):
            count = 0
            while line.get_value() == 0:
                count += 1
                if count > 100:
                    break
            count = 0
            while line.get_value() == 1:
                count += 1
                if count > 100:
                    break
            data.append(count > 10)
        
        humidity = int(''.join(map(str, map(int, data[0:8]))), 2)
        temperature = int(''.join(map(str, map(int, data[16:24]))), 2)
        
        return temperature, humidity
    
    finally:
        line.release()
        chip.close()

def read_sensor(max_retries=5):
    for _ in range(max_retries):
        try:
            temp_c, humidity = read_dht11_sensor()
            if temp_c is not None and humidity is not None:
                temp_f = temp_c * (9 / 5) + 32
                return temp_c, temp_f, humidity
        except Exception as e:
            print(f"Error reading sensor: {e}", file=sys.stderr)
        time.sleep(2)
    return None, None, None

try:
    temp_c, temp_f, humidity = read_sensor()
    if temp_c is not None:
        print(json.dumps({
            "temperature_c": temp_c,
            "temperature_f": round(temp_f, 1),
            "humidity": humidity
        }))
    else:
        print(json.dumps({"error": "Failed to read sensor data after multiple attempts"}))
except Exception as e:
    print(json.dumps({"error": f"Unexpected error: {str(e)}"}))

Clone this wiki locally