加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
dht11.py 1.63 KB
一键复制 编辑 原始数据 按行查看 历史
Walkline 提交于 2021-09-13 15:34 . 增加 dht11 文件
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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化