ESP8266 connects to the free public MQTT broker

2020-05-22

MQTT is a lightweight and flexible protocol to exchange IoT messages and deliver data. It dedicates to achieve a balance between flexibility and hardware/network resources for the IoT developer.

ESP8266 provides a highly integrated Wi-Fi SoC solution. Its low-power, compact design and high stability can meet user's requirements. ESP8266 has a complete and self-contained Wi-Fi network function, which can be applied independently, or can run as a slave at another host MCU.

In this project, we will implement connecting ESP8266 to free public MQTT broker operated and maintained by EMQ X Cloud , and programming ESP8266 by using Arduino IDE. EMQ X Cloud is a MQTT IoT cloud service platform with security launched by EMQ, It provides one-stop operation and maintenance agency, and MQTT 5.0 access service with uniquely isolated environment.

The required IoT components

  • ESP8266
  • Arduino IDE
  • MQTT X: an elegant cross-platform MQTT 5.0 client tool
  • The free public MQTT broker
    • Broker: broker.emqx.io
    • TCP Port: 1883
    • Websocket Port: 8083

ESP8266 Pub/Sub

project.png

The code

  1. Firstly, we import libraries ESP8266WiFi and PubSubClient. ESP8266WiFi library can connect ESP8266 to Wi-Fi network, PubSubClient library can enable ESP8266 to connect to MQTT broker for publishing messages and subscribing topics.

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    
  2. Set Wi-Fi name and password, and connection address and port of MQTT broker

    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 for facilitating to output the result of the program, and connecting to the 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 MQTT broker, write callback function, and print connection information on the serial monitor at the same time.

    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 successfully connecting to MQTT broker, ESP8266 will publish messages and subscribe topics, to the MQTT broker.

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

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

The connection and test of MQTT broker

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

    esp_con.png

  2. Establish the connection between MQTT X client and MQTT broker, and send messages to ESP8266

    mqttx_pub.png

  3. View the messages ESP8266 received, in the serial monitor

    esp_msg.png

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

Summary

So far, we have successfully connected ESP8266 to the free public MQTT broker provided by EMQ X Cloud. In this project, we simply connect ESP8266 to the MQTT broker, which is one of the relatively basic capabilities of ESP8266. Besides that, ESP8266 can also connect to various IoT sensors, and report the sensor data to the MQTT broker.

We will release more articles related to IoT development and ESP8266. Stay tuned