Skip to content
김선영 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())

Clone this wiki locally