代码拉取完成,页面将自动刷新
from machine import Pin
import dht
class DHT11Exception(BaseException):
pass
class DHT11(object):
"""
DHT11 驱动
"""
def __init__(self, dataline=None):
assert dataline is not None and isinstance(dataline, int), DHT11Exception("dataline must be a int")
self.__dht11 = dht.DHT11(Pin(dataline))
def deinit(self):
self.__dht11 = None
def temperature(self):
"""
获取温度
"""
temperature = -273.15
try:
self.__dht11.measure()
temperature = self.__dht11.temperature()
except OSError as ose:
if str(ose) == "[Errno 110] ETIMEDOUT":
raise DHT11Exception("DHT11 connection error")
return temperature
def humidity(self):
"""
获取湿度
"""
humidity = 0
try:
self.__dht11.measure()
humidity = self.__dht11.humidity()
except OSError as ose:
if str(ose) == "[Errno 110] ETIMEDOUT":
raise DHT11Exception("DHT11 connection error")
return humidity
def temperature_and_humidity(self):
"""
获取温湿度
"""
result = {"temp": -273.15, "humi": 0}
try:
self.__dht11.measure()
result.update({"temp": self.__dht11.temperature()})
result.update({"humi": self.__dht11.humidity()})
except OSError as ose:
if str(ose) == "[Errno 110] ETIMEDOUT":
raise DHT11Exception("DHT11 connection error")
return result
def run_test():
from utime import sleep_ms
dht11 = DHT11(4)
print("temperature: {}(°C)".format(dht11.temperature()))
sleep_ms(1000)
print("humidity: {}(%)".format(dht11.humidity()))
sleep_ms(1000)
print("temperature: {temp}(°C) and humidity: {humi}(%)".format(**dht11.temperature_and_humidity()))
if __name__ == "__main__":
run_test()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。