DHT11/DHT12溫溼度傳感器實驗-micropython
tags: micropython
dht11/dht12
基本介紹和實驗參考-https://esp32-blairan.blogspot.com/2021/07/dht11dht12-esp32.html
import dht
from machine import Pin
from time import sleep
def measureTemp():
sensor=dht.DHT11(Pin(4))
while True:
try:
sleep(2)
sensor.measure()
t=sensor.temperature()
t_f=t*(9/5)+32
h=sensor.humidity()
print("Temp: {:.1f}.C".format(t))
print("Temp: {:.1f}.F".format(t_f))
print("Humidity: {:.1f}".format(h))
except OSError as o:
print("Failed to read sensor.")
if __name__ == '__main__':
measureTemp()
載入dht庫(內建)
import dht
from machine import Pin
from time import sleep
指定DHT11腳位給sensor變數
sensor=dht.DHT11(Pin(4))
給予while()每2秒不斷偵測
sleep(2)
sensor.measure()
攝氏溫度(t)/華氏溫度(t_f)/濕度
其中攝氏轉換華氏的公式:攝氏x(9/5)+32
t=sensor.temperature()
t_f=t*(9/5)+32
h=sensor.humidity()
print("Temp: {:.1f}.C".format(t))
print("Temp: {:.1f}.F".format(t_f))
print("Humidity: {:.1f}".format(h))
結果
=== Temp: 26.0.C
Temp: 78.8.F
Humidity: 27.0
Temp: 26.0.C
Temp: 78.8.F
Humidity: 27.0
Temp: 26.0.C
Temp: 78.8.F
Humidity: 27.0