Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Use MQTT With the Raspberry Pi and ESP8266 #3

Open
zibuyu1995 opened this issue Oct 22, 2019 · 0 comments
Open

How to Use MQTT With the Raspberry Pi and ESP8266 #3

zibuyu1995 opened this issue Oct 22, 2019 · 0 comments
Assignees
Labels

Comments

@zibuyu1995
Copy link
Owner

zibuyu1995 commented Oct 22, 2019

使用 NodeMCU 和 DHT11 传感器通过 MQTT 上传温湿度数据

简介

本示例将演示如何通过 NodeMCU, DHT11 收集温湿度并通过 MQTT 协议将数据上报到 EMQX MQTT broker。
DHT11数字温湿度传感器是一款含有已校准数字信号输出的温湿度复合传感器,
Node MCU 底层集成了 ESP8266, 能提供完整且自成体系的Wi-Fi网络解决方案,
MQTT 是基于 发布(Publish)/订阅(Subscribe) 模式来进行通信及数据交换的,
EMQX 是基于 Erlang 的 MQTT broker 在开源社区中是最成熟的 MQTT 消息中间件, 它易于配置和使用,可很好地扩展。

配置

硬件配置
  • NodeMCU board x 1
  • DHT11 temperature/humidity sensor x 1
  • Breadboard x 1
  • jumper wires
  • Connection Graph:
    image
Arduino 配置
  • 下载并安装 CH340G USB 驱动
  • 安装 Esp8266模块
  • 安装 PubSubClient 库(by Nick O'Leary)
    Sketch -> Include Library -> Manage Libraries... -> Type PubSub in Search field -> Install
MQTT broker 配置
unzip emqx-macosx-v3.2.5.zip
cd emqx
./bin/emqx start

代码编写

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#include "DHT.h"

#define DHTPIN D4     // what pin we're connected to
#define wifi_ssid "xxxxx"
#define wifi_password "xxxxx"

#define mqtt_server "broker.emqx.io"  // emqx broker url
#define humidity_topic "humidity"
#define temperature_topic "temperature"

#define DHTTYPE DHT11   // DHT 11

WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(115200);
    setup_wifi();
    client.setServer(mqtt_server, 1883);
    dht.begin();
}

void setup_wifi() {
    delay(10);
    WiFi.begin(wifi_ssid, wifi_password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
}

void reconnect() {
    // Loop until we're reconnected
    while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        if (client.connect("nodeMcuDHT11")) {
            Serial.println("connected");
        } else {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
        }
    }
}

bool checkBound(float newValue, float prevValue, float maxDiff) {
    return newValue < prevValue - maxDiff || newValue > prevValue + maxDiff;
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;

void loop() {
    if (!client.connected()) {
        reconnect();
    }
    client.loop();

    long now = millis();
    if (now - lastMsg > 30000) {
        // Wait a few seconds between measurements
        lastMsg = now;

        float newTemp = dht.readTemperature();
        float newHum = dht.readHumidity();
        if (checkBound(newTemp, temp, diff)) {
            temp = newTemp;
            Serial.print("New temperature:");
            Serial.println(String(temp).c_str());
            client.publish(temperature_topic, String(temp).c_str(), true);
        }

        if (checkBound(newHum, hum, diff)) {
            hum = newHum;
            Serial.print("New humidity:");
            Serial.println(String(hum).c_str());
            client.publish(humidity_topic, String(hum).c_str(), true);
        }
    }
}

按照以下操作编辑代码以适合您自己的WIFI和MQTT设置

  • WIFI 设置

    #define wifi_ssid ""
    #define wifi_password ""
  • EMQX MQTT broker 服务器设置

    #define mqtt_server "broker.emqx.io"
  • Arduion 配置

    image

运行

  • 代码上传

    将Node Mcu 通过 usb 连接到PC 并在Arduion IDE中选择 115200 端口,使用upload 按钮编译草图并将其上传到设备

  • 打开 Arduino monitor window 查看数据上报

    image

  • 打开 EMQX Dashboard 查看设备 Node Mcu 连接情况

    User: admin Password: public

    image

  • 利用 EMQX Websockt 工具查看DHT11 上报的温湿度数据

    image

  • 故障排除

    为了执行故障排除,然后将 USB 适配器与 PC 连接并在 Arduino IDE 中选择USB-TTL适配器的端口。打开“串行监视器”以查看由串行输出产生的调试信息。

refer

http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/
https://www.open-homeautomation.com/2016/06/10/program-an-esp8266-from-arduino-on-macos/
https://www.instructables.com/id/NodeMCU-IoT-Project-DHT11/
http://osoyoo.com/2018/01/17/nodemcu-dht11-mqtt/
https://codebender.cc/sketch:316691#esp8266%20dht11%20mqtt%20-%20working.ino
https://www.home-assistant.io/blog/2015/10/11/measure-temperature-with-esp8266-and-report-to-mqtt/
https://thingsboard.io/docs/samples/esp8266/temperature/
https://www.instructables.com/id/Wireless-Temperature-and-Humidity-Monitor-With-ESP/
https://create.arduino.cc/projecthub/thingsboard/temperature-dashboard-using-arduino-uno-esp8266-and-mqtt-5e26eb
https://codebender.cc/sketch:316691#esp8266%20dht11%20mqtt%20-%20working.ino

@zibuyu1995 zibuyu1995 self-assigned this Oct 22, 2019
@zibuyu1995 zibuyu1995 reopened this Nov 17, 2019
@zibuyu1995 zibuyu1995 reopened this Nov 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant