Skip to content
김선영 edited this page Oct 15, 2024 · 5 revisions

import time import json import gpiod import sys

DHT11 센서가 연결된 GPIO 핀 번호 (BCM 번호 체계 사용)

DHT_PIN = 4 # GPIO 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