ESP8266采集DHT11温湿度数据

by - 十一月 24, 2016



项目描述:闲来无事,制作一个用ESP8266控制DHT11采集温度,湿度并在OLED屏显示的系统,使用了MQTT协议,编程语言使用Micropython.巩固一下所学到的一些知识。
<!-- more -->

一、项目准备

1.所需材料

  • DHT11温湿度传感器
  • NUDEMCU开发板
  • OLED 彩屏
  • 小灯,电阻,面包板,导线若干

2.开发环境

  • Micropython
  • MQTT

二、项目制作

1.电路连接图

2016112455717wenshidu.png
按照如上电路图连接,其中NUDEMCUUSB连接电脑USB.

2.编写main.py文件

from machine import Pin,I2C
from time import sleep_ms
from ubinascii import hexlify
from umqtt.simple import MQTTClient
from dht import DHT11
from ssd1306 import SSD1306_I2C
import machine
#---MQTT Sending---
SERVER="iot.eclipse.org"
CLIENT_TD=hexlify(machine.unique_id())
led = Pin(2, Pin.OUT, value=1)

TOPIC1=b"/dht11/tem"
TOPIC2=b"/dht11/hum"
TOPIC3=b"/dht11/led"

def envioMQTT(server=SERVER,topic="/foo",data=None):
    try:
        c=MQTTClient(CLIENT_TD,server)
        c.connect()
        c.publish(topic,data)
        sleep_ms(200)
        c.disconnect()
    except Exception as e:
        pass

state=0
def sub_cb(topic,msg):
    global state
    print((topic,msg))
    if msg==b"on":
        led.value(0)
        state=1
    elif msg=b"off":
        led.value(1)
        state=0

def recepcionMQTT(server=SERVER,topic=TOPIC3):
    c.MQTTClient(CLIENT_TD,server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(topic)
    try:
        c.wait_msg()
    finally:
        c.disconnect()
#---End MQTT Sending---

#---DHT11---
ds=DHT11(Pin(16))
def medirTemHum():
    try:
        ds.measure()
        tem=ds.temperature()
        hum=ds.humidity()
        return (tem,hum)
    except Exception as e:
        return (-1,-1)
#---End DHT11---

#---OLED IIC 128x64---
i2c = I2C(sda = Pin(4), scl = Pin(5))
display = SSD1306_I2C(128, 64, i2c)
def displaytem(tem,hum):
    display.fill(0)
    temperatura = 'Tem: ' + str(tem)[:5] + 'C'
    humedad = 'Hum: ' + str(hum)[:5] + '%'
    display.text(temperatura,2,2,1)
    display.text(humedad,2,14,1)
    display.show()
#---End OLED---

#---Main Program---
sleep_ms(10000)
while True:
    (tem,hum) = medirTemHum()
    displaytem(tem,hum)
    envioMQTT(SERVER,TOPIC1,str(tem))
    envioMQTT(SERVER,TOPIC2,str(hum))
    recepcionMQTT()
    sleep_ms(10000)
#---END Main Program---

3.项目描述

  • 使用了iot.eclipse.orgMQTT服务;
  • ESP8266运行的是Micropython的固件,需自行烧写;
  • main.py文件使用 Micropythonwebrepl服务上传,复位后自动运行;
  • 手机端下载一个MQTT Client ,连上iot.eclipse.org,并且订阅这些消息便可以看到收到的信息。 效果如下所示: 2016112581569tem_hum.png

三、参考连接

1.webrepl:http://micropython.org/webrepl/
2.MQTT Server:http://mqtt.org/documentation
3.iot.eclipse:http://iot.eclipse.org

You May Also Like

0 评论