当前位置:   article > 正文

ThingsBoard通过ESp8266(MicroPython固件)获取DHT11温湿度_esp8266 python mqtt

esp8266 python mqtt

ThingsBoard通过ESp8266(MicroPython固件)获取DHT11温湿度

1、将以下代码上传到ESP8266

1、上传代码之前必须确保自己的ESP8266(以下统称WIFI模块)的固件版本是MicroPython,如果不是【请看此文章】。
2、刷如固件后看这篇文章的步骤将以下代码上传到WIFI模块
3、导入所需库simple.py,直接将下载的文件上传到WiFi模块内

import network
import time
import dht
import machine
import json
import ubinascii
from simple import MQTTClient


SSID="WIFI名称"
PASSWORD="WiFi密码"

CLIENT_ID = ubinascii.hexlify(machine.unique_id())

CONFIG = {
    "server": "192.168.1.57",  // ThingsBoard地址
    "port":1883,  // MQTT端口(默认1883"mqtt_user": "Jy4MRL5P1o7YV90PhKcR",  // 设备的访问令牌
    "mqtt_password": "Jy4MRL5P1o7YV90PhKcR",  // 设备的访问令牌
    "mqtt_topic": "v1/devices/me/telemetry",  // MQTT主题(无需更改)
}

//连接WiFi函数
def connectWifi(ssid,passwd):
    global wlan
    wlan=network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.disconnect()
    wlan.connect(ssid,passwd)
    while(wlan.ifconfig()[0]=='0.0.0.0'):
        time.sleep(1)

//获取温湿度函数
def get_humiture():
    d = dht.DHT11(machine.Pin(2))
    d.measure()
    return d.temperature(),d.humidity()

//上传温湿度到ThingsBoard函数
def pub_humiture(humidity, temperature):
    global c
    data={'humidity':humidity, 'temperature':temperature} 
    c.publish(CONFIG["mqtt_topic"], json.dumps(data))
    print(json.dumps(data))


def main():
    connectWifi(SSID,PASSWORD)
    global c
    c = MQTTClient(CLIENT_ID, CONFIG["server"],CONFIG["port"], CONFIG["mqtt_user"], CONFIG["mqtt_password"])
    c.connect()
    print("Connected to %s, publish to %s topic" % (CONFIG["server"], CONFIG["mqtt_topic"]))
    while True:
        tem, hum=get_humiture()
        pub_humiture(hum, tem)
        time.sleep(5)    

if __name__ == "__main__":
    main()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

在这里插入图片描述

2、实物连接

WiFi模块的 IO2 连接DHT11的 OUT,其他的只要把正负接对,还有就是尽量将WiFi模块和DHT11接在同一个电路中,否则可能出现DHT11无法读取数据,切记WiFi模块一定要接3.3V。
大概连接图如下:
在这里插入图片描述

2、测试是否可以正常获取温度

根据下图顺序操作后看到左侧输出以下内容可以确定ESP8266可以获取到温湿度

在这里插入图片描述
最后在Things board平台的最新遥测中知否能看到温度和湿度。

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/718206
推荐阅读
相关标签
  

闽ICP备14008679号