使用 NodeMCU 和 DHT11 傳感器通過 MQTT 上傳溫溼度數據

使用 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適配器的端口。打開“串行監視器”以查看由串行輸出產生的調試信息。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章