MicroPython讀取DHT11
|
本例使用的是單匯流排模式。
接線如下:
VDD->3V3
SDA->pin(4) ===> NodeMcu D2
GND->GND
SCL->GND
接線如下:
VDD->3V3
SDA->pin(4) ===> NodeMcu D2
GND->GND
SCL->GND
#==================DHT11.py=====================
#Pin(4) == D2
#=================
import DHTsensor
import machine
import time
d = DHTsensor.DHT11(machine.Pin(4))
while True:
d.measure()
print("temperature :",d.temperature())
time.sleep(1)
print("humidity :",d.humidity())
#==================DHTsencor.py===================
import esp
class DHTBase:
def __init__(self, pin):
self.pin = pin
self.buf = bytearray(5)
def measure(self):
buf = self.buf
esp.dht_readinto(self.pin, buf)
if (buf[0] + buf[1] + buf[2] + buf[3]) & 0xff != buf[4]:
raise Exception("checksum error")
class DHT11(DHTBase):
def humidity(self):
return self.buf[0]
def temperature(self):
return self.buf[2]
class DHT12(DHTBase):
def humidity(self):
return self.buf[0] + self.buf[1] * 0.1
def temperature(self):
t = self.buf[2] + self.buf[3] * 0.1
if self.buf[2] & 0x80:
t = -t
return t
class DHT22(DHTBase):
def humidity(self):
return (self.buf[0] << 8 | self.buf[1]) * 0.1
def temperature(self):
t = ((self.buf[2] & 0x7f) << 8 | self.buf[3]) * 0.1
if self.buf[2] & 0x80:
t = -t
return t
沒有留言:
張貼留言