Free EMQ X MQTT server to which ESP8266 connects

MQTT is a lightweight and flexible IoT message exchange and data transfer protocol, dedicated to achieving a balance between flexibility and hardware/network resources for IoT developers.

ESP8266 provides a set of highly integrated Wi-Fi SoC solutions. Its low power consumption, compact design and high stability can meet the needs of users. ESP8266 has a complete and self-contained Wi-Fi network function, which can be used independently or run as a slave on other host MCUs.

In this project, we will connect ESP8266 to a free public MQTT server operated and maintained by EMQ X Cloud , and use Arduino IDE to program ESP8266. EMQ X Cloud is a secure MQTT IoT cloud service platform launched by EMQ . It provides one-stop operation and maintenance management and unique isolation environment MQTT 5.0 access service.

Required IoT components

  • ESP8266
  • Arduino IDE
  • MQTT X : Elegant cross-platform MQTT 5.0 client tool
  • Free public MQTT server
    • Broker: broker.emqx.io
    • TCP Port: 1883
    • Websocket Port: 8083

ESP8266 Pub/Sub schematic

Insert picture description here

ESP8266 code writing

  1. First, we will import the ESP8266WiFi and PubSubClient libraries. The ESP8266WiFi library can connect the ESP8266 to the Wi-Fi network, and the PubSubClient library can connect the ESP8266 to the MQTT server to publish messages and subscribe to topics.

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    
  2. Set the Wi-Fi name and password, as well as the MQTT server connection address and port

    const char *ssid = "name"; // Enter your WiFi name
    const char *password = "pass";  // Enter WiFi password
    const char *mqtt_broker = "broker.emqx.io";
    const int mqtt_port = 1883;
    
  3. Open a serial connection to output the results of the program and connect to a Wi-Fi 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..");
    }
    
  4. Set up the MQTT server, write a callback function, and print the connection information to the serial monitor

    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
          
          
        Serial.println("Connecting to public emqx mqtt broker.....");
        if (client.connect("esp8266-client")) {
          
          
            Serial.println("Public emqx mqtt broker connected");
        } else {
          
          
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    
    void callback(char *topic, byte *payload, unsigned int length) {
          
          
        Serial.print("Message arrived in topic: ");
        Serial.println(topic);
        Serial.print("Message:");
        for (int i = 0; i < length; i++) {
          
          
            Serial.print((char) payload[i]);
        }
        Serial.println();
        Serial.println("-----------------------");
    }
    
  5. After the MQTT server is successfully connected, ESP8266 will publish messages and subscribe topics to the MQTT server

    // publish and subscribe
    client.publish("esp8266/test", "hello emqx");
    client.subscribe("esp8266/test");
    
  6. Print the subject name to the serial port, and then print every byte of the received message

    void callback(char *topic, byte *payload, unsigned int length) {
          
          
        Serial.print("Message arrived in topic: ");
        Serial.println(topic);
        Serial.print("Message:");
        for (int i = 0; i < length; i++) {
          
          
            Serial.print((char) payload[i]);
        }
        Serial.println();
        Serial.println("-----------------------");
    }
    

MQTT server connection and testing

  1. Please use Arduino IDE to upload the complete code to ESP8266 and open the serial monitor

    Insert picture description here

  2. Establish a connection between MQTT X client and MQTT server, and send messages to ESP8266

Insert picture description here

  1. View the messages received by ESP8266 on the serial monitor

    Insert picture description here

Complete code

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

const char *ssid = "name"; // Enter your WiFi name
const char *password = "pass";  // Enter WiFi password
const char *mqtt_broker = "broker.emqx.io";
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()) {
    
    
        Serial.println("Connecting to public emqx mqtt broker.....");
        if (client.connect("esp8266-client")) {
    
    
            Serial.println("Public emqx mqtt broker connected");
        } else {
    
    
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    // publish and subscribe
    client.publish("esp8266/test", "hello emqx");
    client.subscribe("esp8266/test");
}

void callback(char *topic, byte *payload, unsigned int length) {
    
    
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (int i = 0; i < length; i++) {
    
    
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}

void loop() {
    
    
    client.loop();
}

to sum up

So far, we have successfully connected ESP8266 to the public MQTT server provided by EMQ X Cloud. In this project, we simply connect ESP8266 to the MQTT server. This is just one of ESP8266's basic capabilities. ESP8266 can actually connect to various IoT sensors and report sensor data to the MQTT server.

Next, we will publish more articles about IoT development and ESP8266, please pay attention.

Copyright statement: This article is EMQ original, please indicate the source for reprinting

Original link: https://www.emqx.io/cn/blog/esp8266-connects-to-the-public-mqtt-broker

Guess you like

Origin blog.csdn.net/emqx_broker/article/details/106250683