创客.掌控板.温湿度传感器

DHT11/22温湿度传感器

# 功能:DHT11/DHT22温湿度计
# 实验:将DHT11接在P0上或将DHT22接在P1上
#       串口和屏幕都输出两个传感器的温湿度
#注意事项:measure方法不能频繁被调用,示例中1秒一次

from mpython import *
import dht
import time

dht11Pin = MPythonPin(0)
#dht22Pin = MPythonPin(1)

dht11 = dht.DHT11(dht11Pin.Pin)
#dht22 = dht.DHT22(dht22Pin.Pin)

oled.DispChar("DHT11", 0, 0)
#oled.DispChar("DHT22", 0, 32)

while True:
    try:
        dht11.measure()
    except:
        oled.DispChar("请连接dht11硬件",16, 16)
        oled.show()
        sleep(1)
        continue
    t = dht11.temperature() # eg. 23 (℃)
    h = dht11.humidity()    # eg. 41 (% RH)
    oled.DispChar("温度=%d℃ 湿度=%d"%(t,h),16, 16)
    oled.show()
    print("DHT11 温度=%d℃ 湿度=%d RH"%(t,h))

    #dht22.measure()  
    #t = dht22.temperature() # eg. 23.6 (°C)
    #h = dht22.humidity()    # eg. 41.3 (% RH)
    #oled.DispChar("温度=%d 湿度=%d"%(t,h),16, 48)
    #oled.show()
    #print("DHT22 温度=%d 湿度=%d"%(t,h))
    time.sleep(1)

此代码针对DHT11或DHT22温湿度传感器,可以在屏幕上显示温湿度,注意板子P0如果连接了喇叭需要关闭。

 

网友留言(0 条)

发表评论

验证码