美文网首页
Esp8266 接受订阅,控制输出

Esp8266 接受订阅,控制输出

作者: qy_ffa1 | 来源:发表于2022-06-18 21:18 被阅读0次

    发布信息,控制ESP8266管脚电压,实现控制。

    #include <ESP8266WiFi.h>

    #include <PubSubClient.h>

    #define LED D8

    // WiFi

    const char *ssid = "XXXX"; // Enter your WiFi name

    const char *password = "XXXXXX";  // Enter WiFi password

    // MQTT Broker

    const char *mqtt_broker = "192.168.3.200";

    const char *topic = "led"; //订阅主题

    const char *mqtt_username = "emqx";

    const char *mqtt_password = " ";

    const int mqtt_port = 1883;

    WiFiClient espClient;

    PubSubClient client(espClient);

    void setup() {

        // Set software serial baud to 115200;

        Serial.begin(115200);

        pinMode(LED,OUTPUT);

        // 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.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());

            if (client.connect(client_id.c_str(), 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, HIGH); }  // LED on

        if (message == "off") { digitalWrite(LED, LOW); } // LED off

    //    Serial.print("hello ");

        Serial.println();

        Serial.println("-----------------------");

    }

    void loop() {

        client.loop();

    }

    只要发送  on 或 off 给  订阅主题  led ,就能控制D8 脚 的高低电平,实现控制。

    相关文章

      网友评论

          本文标题:Esp8266 接受订阅,控制输出

          本文链接:https://www.haomeiwen.com/subject/isrlvrtx.html