raspberryPiModuleExpansionT.../tutorial/1.dht11_sensor.py

38 lines
1.3 KiB
Python

import time
import board
import adafruit_dht
# DHT11 센서가 연결된 GPIO 핀 번호를 설정합니다.
# board.D4는 GPIO 4를 의미합니다.
# 다른 핀에 연결했다면 board.D{핀번호} 로 변경하세요.
dhtDevice = adafruit_dht.DHT11(board.D4)
while True:
try:
# 센서에서 온도 (섭씨)와 습도 값을 읽어옵니다.
temperature_c = dhtDevice.temperature
humidity = dhtDevice.humidity
# 섭씨 온도를 화씨 온도로 변환 (선택 사항)
temperature_f = temperature_c * (9 / 5) + 32
# 값을 출력합니다.
print(
"온도: {:.1f} C / {:.1f} F 습도: {}%".format(
temperature_c, temperature_f, humidity
)
)
except RuntimeError as error:
# DHT 센서 읽기 오류는 흔하게 발생할 수 있습니다.
# 이런 오류가 발생하면 에러 메시지를 출력하고 2초 후에 다시 시도합니다.
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
# 다른 예외가 발생하면 센서를 정리하고 프로그램을 종료합니다.
dhtDevice.exit()
raise error
time.sleep(2.0) # 2초마다 센서 값을 읽습니다.