温湿度センサーの使い方
温湿度センサー(DHT11)を用いて温湿度を取得して2秒毎に表示させます。
コード
import machine
import time
import dht
# DHT11センサーの設定
dht_pin = machine.Pin(4)
dht_sensor = dht.DHT11(dht_pin)
def read_dht11():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
return temp, hum
except OSError as e:
print('Failed to read DHT11 sensor:', e)
return None, None
while True:
temp, hum = read_dht11()
if temp is not None and hum is not None:
print('Temperature: {}°C, Humidity: {}%'.format(temp, hum))
else:
print('Failed to get temperature and humidity.')
time.sleep(2)
カテゴリ
タグ
参考図