溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制

發(fā)布時(shí)間:2021-12-06 16:53:04 來(lái)源:億速云 閱讀:632 作者:iii 欄目:互聯(lián)網(wǎng)科技

這篇文章主要講解了“ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制”吧!

MQTT 是輕量級(jí)的、靈活的物聯(lián)網(wǎng)消息交換和數(shù)據(jù)傳遞協(xié)議,致力于為 IoT 開發(fā)人員實(shí)現(xiàn)靈活性與硬件/網(wǎng)絡(luò)資源的平衡。

NodeMCU 是一個(gè)開源的物聯(lián)網(wǎng)平臺(tái)。它使用 Lua 語(yǔ)言編程。該平臺(tái)基于eLua開源項(xiàng)目,底層使用ESP8266 sdk 0.9.5版本。

在此項(xiàng)目中我們將實(shí)現(xiàn) NodeMCU(ESP8266) 與 EMQ X Cloud 運(yùn)營(yíng)和維護(hù)的免費(fèi)公共 MQTT 服務(wù)器遠(yuǎn)程控制 LED 燈,并使用 Arduino IDE 來(lái)對(duì) NodeMCU ESP8266 進(jìn)行編程。 EMQ X Cloud 是由 EMQ 推出的安全的 MQTT 物聯(lián)網(wǎng)云服務(wù)平臺(tái),它提供一站式運(yùn)維代管、獨(dú)有隔離環(huán)境的 MQTT 5.0 接入服務(wù)。

所需組件

  • NodeMCU

  • Arduino IDE

  • LED * 1,330 Ω 電阻

  • MQTT X: 優(yōu)雅的跨平臺(tái) MQTT 5.0 客戶端工具

  • 免費(fèi)的公共 MQTT 服務(wù)器

    • Broker: broker.emqx.io

    • TCP Port: 1883

    • Websocket Port: 8083

NodeMCU ESP8266 和 LED 連接圖

ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制

代碼編寫

  1. 首先我們將導(dǎo)入 ESP8266WiFiPubSubClient 庫(kù),ESP8266WiFi 庫(kù)能夠?qū)?ESP8266 連接到 WiFi 網(wǎng)絡(luò),PubSubClient 庫(kù),使我們能夠連接到 MQTT 代理并發(fā)布/訂閱主題消息。

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>


  2. 我們將使用 NodeMCU ESP8266 的 D1 引腳來(lái)連接到 LED,實(shí)際上該引腳內(nèi)部連接到 ESP8266 模塊的 GPIO5。

    // GPIO 5 D1
    #define LED 5


  3. 設(shè)置 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. 我們打開了一個(gè)串行連接,以便于輸出程序的結(jié)果并且連接到WiFi網(wǎng)絡(luò)

    // 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. 我們將設(shè)置 MQTT Broker,同時(shí)將連接信息打印到串口監(jiān)視器上

     //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 發(fā)布和訂閱消息

    // publish and subscribe
    client.publish(topic, "hello emqx");
    client.subscribe(topic);


  7. 編寫回調(diào)函數(shù),從串行監(jiān)視器讀取下發(fā)指令并且控制 LED 的開和關(guān)

    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();
    }


連接和測(cè)試

  1. 請(qǐng)使用 Arduino IDE 將完整代碼上傳 ESP8266,并打開串口監(jiān)視器

    ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制

  2. 建立 MQTTX 客戶端 與 MQTT Broker 連接, 并向 ESP8266 發(fā)送指令

    ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制

感謝各位的閱讀,以上就是“ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)ESP8266+MQTT怎么實(shí)現(xiàn)LED燈的遠(yuǎn)程控制這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI