DHT11和DHT22都是价廉物美的温度湿度传感器(DHT (Digital Humidity & Temperature) sensors), 采用数字总线的通讯方式,非常便于编程. 另外显示采用SSD1306的olde显示屏,这也是一款常用的显示设备,采用IIC或SPI通讯,库也很丰富,使用起来也是很简单.
我通过采集DHT22,读取温度和湿度数据,再通过oled屏显示出来,这就是一款温度湿度检测设备.
00. 采用 micropython和esp8266芯片.
原件如下:
01.代码如下:
import ssd1306
import dht
import utime
import machine
from machine import I2C, Pin
d = dht.DHT22(machine.Pin(4))
i2c = I2C(-1, Pin(14), Pin(12))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
def mshow():
d.measure()
t0 = str(d.temperature()) + 'C'
h0 = str(d.humidity()) + '%'
utime.sleep(3)
display.fill(0)
display.text('TH Sensor', 4, 1)
display.text('Temperature:', 1, 17)
display.text('Humidity:', 1, 33)
display.text('Gaoshine 201712', 1, 57)
display.text(t0, 12*8, 17)
display.text(h0, 10*8, 33)
display.show()
def main():
while True:
mshow()
utime.sleep(1)
if __name__ == "__main__":
main()
代码的结构:
02. 运行效果:
03. 增加时钟功能
芯片本身是支持RTC的,不过复位或掉电后系统就回到2000年,比较好的办法采用 NTP服务,每次启动从NTP服务器上获取时间,再同步时钟.
代码如下:
import ssd1306
import dht
import utime
import machine
import ntptime
from machine import I2C, Pin
t = ntptime.time()
ntptime.settime()
d = dht.DHT22(machine.Pin(4))
i2c = I2C(-1, Pin(14), Pin(12))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
def mshow():
d.measure()
t0 = str(d.temperature()) + 'C'
h0 = str(d.humidity()) + '%'
utime.sleep(3)
display.fill(0)
display.text('TH Sensor', 4, 1)
display.text('Temperature:', 1, 17)
display.text('Humidity:', 1, 33)
display.text(t0, 12*8, 17)
display.text(h0, 10*8, 33)
ts = utime.localtime()
s = '%s-%s-%s %s:%s' % (ts[0], ts[1], ts[2], ts[3]+8, ts[4])
display.text(s, 1, 57)
display.show()
def main():
while True:
mshow()
utime.sleep(1)
if __name__ == "__main__":
main()