MQTT is a lightweight, flexible IoT message exchange and data delivery protocol that balances flexibility with hardware/network resources for IoT developers.

NodeMCU is an open source Internet of Things platform. It is programmed using the Lua language. The platform is based on the eLua open source project, using ESP8266 SDK 0.9.5.

In this project, we will implement a free public MQTT server operated and maintained by NodeMCU(ESP8266) and EMQ X Cloud to remotely control LED lights and program NodeMCU ESP8266 using Arduino IDE. EMQ X Cloud is a secure MQTT iot Cloud service platform launched by EMQ. It provides one-stop operation and maintenance escrow and unique isolated environment MQTT 5.0 access service.

The required components

  • NodeMCU
  • Arduino IDE
  • LED * 1,330 ω resistance
  • MQTT X: Elegant cross-platform MQTT 5.0 client tool
  • Free public MQTT server
    • Broker: broker.emqx.io
    • TCP Port: 1883
    • Websocket Port: 8083

NodeMCU ESP8266 and LED connection diagram

The code

  1. First we will import the ESP8266WiFi library, which connects ESP8266 to WiFi networks, and the PubSubClient library, which enables us to connect to MQTT broker and publish/subscribe topic messages.

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    Copy the code
  2. We will use the NodeMCU ESP8266’S D1 pin to connect to the LED, which is actually internally connected to the ESP8266 module’s GPIO5.

    // GPIO 5 D1
    #define LED 5
    Copy the code
  3. Set the WIFI name and password, and the MQTT Broker connection address and port

    // 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;
    Copy the code
  4. We open a serial connection to output the results of the program and connect to the WiFi network

    // 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..");
    }
    Copy the code
  5. We will set up the MQTT Broker and print the connection information to the serial port monitor

     //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); }}Copy the code
  6. After the MQTT Broker connection is successful, ESP8266 will publish and subscribe messages to the MQTT Broker

    // publish and subscribe
    client.publish(topic, "hello emqx");
    client.subscribe(topic);
    Copy the code
  7. Write callback functions that read the delivery instructions from the serial monitor and control the LED on and off

    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("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
    }
    Copy the code
  8. The complete code

    #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(a) {
        // 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(a) {
        client.loop();
    }
    Copy the code

Connect and test

  1. Upload the complete code to ESP8266 using the Arduino IDE and turn on the serial port monitor

  2. Establish an MQTTX client to connect to the MQTT Broker and send instructions to ESP8266

conclusion

So far, we have successfully implemented NodeMCU ESP8266 and the free public MQTT server to remotely control LED lights. This example only describes a simple scenario where a more secure connection is needed in a real project, as well as the ability to persist Internet of Things data.

For more articles related to Internet of Things development and ESP8266, please stay tuned.

Copyright: EMQ

Original link: www.emqx.cn/blog/esp826…