-
Notifications
You must be signed in to change notification settings - Fork 0
memo
김선영 edited this page Oct 15, 2024
·
5 revisions
import time
import board
import adafruit_dht
import json
def read_sensor():
try:
dhtDevice = adafruit_dht.DHT11(board.D4)
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
return json.dumps({
"temperature_c": round(temperature_c, 1),
"temperature_f": round(temperature_f, 1),
"humidity": humidity
})
except RuntimeError as error:
return json.dumps({"error": str(error)})
except Exception as error:
return json.dumps({"error": f"Unexpected error: {str(error)}"})
finally:
dhtDevice.exit()
print(read_sensor())
import time
import board
import adafruit_dht
import json
# 센서 객체 생성
dhtDevice = adafruit_dht.DHT11(board.D4)
def read_sensor():
try:
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
return json.dumps({
"temperature_c": round(temperature_c, 1),
"temperature_f": round(temperature_f, 1),
"humidity": humidity
})
except RuntimeError as error:
return json.dumps({"error": str(error)})
except Exception as error:
return json.dumps({"error": f"Unexpected error: {str(error)}"})
try:
while True:
print(read_sensor())
time.sleep(2) # 2초 대기
except KeyboardInterrupt:
pass
finally:
dhtDevice.exit()