ESP8266 + MQTT :如何實現 LED 燈的遠程控制


MQTT 是輕量級的、靈活的物聯網消息交換和數據傳遞協議,致力於為 IoT 開發人員實現靈活性與硬件/網絡資源的平衡。

NodeMCU 是一個開源的物聯網平台。它使用 Lua 語言編程。該平台基於eLua開源項目,底層使用ESP8266 sdk 0.9.5版本。

在此項目中我們將實現 NodeMCU(ESP8266) 與 EMQ X Cloud 運營和維護的免費公共 MQTT 服務器遠程控制 LED 燈,並使用 Arduino IDE 來對 NodeMCU ESP8266 進行編程。 EMQ X Cloud 是由 EMQ 推出的安全的 MQTT 物聯網雲服務平台,它提供一站式運維代管、獨有隔離環境的 MQTT 5.0 接入服務。

所需組件

  • NodeMCU
  • Arduino IDE
  • LED * 1,330 Ω 電阻
  • MQTT X: 優雅的跨平台 MQTT 5.0 客戶端工具
  • 免費的公共 MQTT 服務器
    • Broker: broker.emqx.io
    • TCP Port: 1883
    • Websocket Port: 8083

NodeMCU ESP8266 和 LED 連接圖

project

代碼編寫

  1. 首先我們將導入 ESP8266WiFiPubSubClient 庫,ESP8266WiFi 庫能夠將 ESP8266 連接到 WiFi 網絡,PubSubClient 庫,使我們能夠連接到 MQTT 代理並發布/訂閱主題消息。

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    
  2. 我們將使用 NodeMCU ESP8266 的 D1 引腳來連接到 LED,實際上該引腳內部連接到 ESP8266 模塊的 GPIO5

    // GPIO 5 D1
    #define LED 5
    
  3. 設置 WIFI 名稱和密碼,以及 MQTT Broker 連接地址和端口

    // WiFi
    const char *ssid = "mousse"; // Enter your WiFi name
    const char *password = "qweqweqwe";  // Enter WiFi password
     
    // MQTT Broker
    const char *mqtt_broker = "broker.emqx.io";
    const char *topic = "esp8266/led";
    const char *mqtt_username = "emqx";
    const char *mqtt_password = "public";
    const int mqtt_port = 1883;
    
  4. 我們打開了一個串行連接,以便於輸出程序的結果並且連接到WiFi網絡

    // Set software serial baud to 115200;
    Serial.begin(115200);
    // connecting to a WiFi network
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi..");
    }
    
  5. 我們將設置 MQTT Broker,同時將連接信息打印到串口監視器上

     //connecting to a mqtt broker
    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        String client_id = "esp8266-client-";
        client_id += String(WiFi.macAddress());
        Serial.println("Connecting to public emqx mqtt broker.....");
        if (client.connect(client_id, mqtt_username, mqtt_password)) {
            Serial.println("Public emqx mqtt broker connected");
        } else {
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    
  6. MQTT Broker 連接成功后,ESP8266 將向 MQTT Broker 發布和訂閱消息

    // publish and subscribe
    client.publish(topic, "hello emqx");
    client.subscribe(topic);
    
  7. 編寫回調函數,從串行監視器讀取下發指令並且控制 LED 的開和關

    void callback(char *topic, byte *payload, unsigned int length) {
        Serial.print("Message arrived in topic: ");
        Serial.println(topic);
        Serial.print("Message:");
        String message;
        for (int i = 0; i < length; i++) {
            message = message + (char) payload[i];  // convert *byte to string
        }
        Serial.print(message);
        if (message == "on") { digitalWrite(LED, LOW); }   // LED on
        if (message == "off") { digitalWrite(LED, HIGH); } // LED off
        Serial.println();
        Serial.println("-----------------------");
    }
    
  8. 完整代碼

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    
    // GPIO 5 D1
    #define LED 5
    
    // WiFi
    const char *ssid = "mousse"; // Enter your WiFi name
    const char *password = "qweqweqwe";  // Enter WiFi password
    
    // MQTT Broker
    const char *mqtt_broker = "broker.emqx.io";
    const char *topic = "esp8266/led";
    const char *mqtt_username = "emqx";
    const char *mqtt_password = "public";
    const int mqtt_port = 1883;
    
    WiFiClient espClient;
    PubSubClient client(espClient);
    
    void setup() {
        // Set software serial baud to 115200;
        Serial.begin(115200);
        // connecting to a WiFi network
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.println("Connecting to WiFi..");
        }
        Serial.println("Connected to the WiFi network");
        //connecting to a mqtt broker
        client.setServer(mqtt_broker, mqtt_port);
        client.setCallback(callback);
        while (!client.connected()) {
            String client_id = "esp8266-client-";
            client_id += String(WiFi.macAddress());
            Serial.println("Connecting to public emqx mqtt broker.....");
            if (client.connect(client_id, mqtt_username, mqtt_password)) {
                Serial.println("Public emqx mqtt broker connected");
            } else {
                Serial.print("failed with state ");
                Serial.print(client.state());
                delay(2000);
            }
        }
        // publish and subscribe
        client.publish(topic, "hello emqx");
        client.subscribe(topic);
    }
    
    void callback(char *topic, byte *payload, unsigned int length) {
        Serial.print("Message arrived in topic: ");
        Serial.println(topic);
        Serial.print("Message:");
        String message;
        for (int i = 0; i < length; i++) {
            message = message + (char) payload[i];  // convert *byte to string
        }
        Serial.print(message);
        if (message == "on") { digitalWrite(LED, LOW); }   // LED on
        if (message == "off") { digitalWrite(LED, HIGH); } // LED off
        Serial.println();
        Serial.println("-----------------------");
    }
    
    void loop() {
        client.loop();
    }
    

連接和測試

  1. 請使用 Arduino IDE 將完整代碼上傳 ESP8266,並打開串口監視器

    esp_con

  2. 建立 MQTTX 客戶端 與 MQTT Broker 連接, 並向 ESP8266 發送指令

    esp_con

總結

至此,我們成功實現 NodeMCU ESP8266 與免費公共 MQTT 服務器遠程控制 LED 燈,該例子只是描述了一個簡單的場景,在實際的項目中,需要更加安全的連接方式,以及對物聯網數據進行持久化等功能。

更多物聯網開發及 ESP8266 相關文章,敬請關注后續推送。

版權聲明: 本文為 EMQ 原創,轉載請注明出處。

原文鏈接:https://www.emqx.cn/blog/esp8266_mqtt_led


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM