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

ESP32 is an upgraded version of ESP8266. In addition to the Wi-Fi module, the module also includes a Bluetooth 4.0 module. With a dual-core CPU operating at 80 to 240 MHz, two Wi-Fi and Bluetooth modules and a variety of input and output pins, the ESP32 is ideal for iot projects.

In this project we will implement ESP32 to connect to a free public MQTT server operated and maintained by the EMQ X MQTT Cloud and program ESP32 using Arduino IDE. EMQ X Cloud is a secure MQTT Internet of Things Cloud service platform launched by EMQ. It provides one-stop operation and maintenance hosting, exclusive isolation environment MQTT 5.0 access services.

Required iot components

  • ESP32
  • Arduino IDE
  • MQTT 5.0 Client tool – MQTT X
  • A free public MQTT server deployed on the EMQ X Cloud

    • Broker: broker-cn.emqx.io
    • TCP Port: 1883
    • Websocket Port: 8083

Arduino configuration

Install the ESP32 development board

Go to Tools -> Development Board -> Development Board Management -> Search ESP32 -> Install

Install the PubSub client

Project -> Load library -> Manage library… -> Search PubSubClient -> Install PubSubClient by Nick O ‘Leary

ESP32 Pub/Sub schematic

ESP32 code writing

Step by step to connect MQTT

  1. The ESP8266WiFi library connects the ESP32 to Wi-Fi networks, and the PubSubClient library connects the ESP32 to MQTT servers to publish messages and subscribe to topics.

    #include <WiFi.h>
    #include <PubSubClient.h>
  2. Set the Wi-Fi name and password, as well as the MQTT server connection address and port, and this topic is “esp32/test”

    // 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 = "esp32/test";
    const char *mqtt_username = "emqx";
    const char *mqtt_password = "public";
    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. Use PubSubClient to connect to the public MQTT Broker.

    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        String client_id = "esp32-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);
        }
    }
  5. Upon successful connection to the MQTT server, ESP32 will publish messages to the MQTT server ESP /test and subscribe to esp/ Test topic messages.

    // publish and subscribe
    client.publish(topic, "Hi EMQ X I'm ESP32 ^^");
    client.subscribe(topic);
  6. Set the callback function to print the topic name to the serial port and print the messages received from the ESP32 / Test topic.

    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 complete code

#include <WiFi.h> #include <PubSubClient.h> // 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 = "esp32/test"; 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 = "esp32-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, "Hi EMQ X I'm ESP32 ^^"); client.subscribe(topic); } 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(); }

Run and test

  1. Upload the full code using Arduino and power up the ESP32
  2. Open the serial port monitor and select 115200 baud rate to view the ESP32 connection

  3. Use the MQTT X client to connect to the public MQTT server and send messages to ESP32

conclusion

At this point, we have successfully connected ESP32 to the public MQTT server provided by the EMQ X Cloud. In this project we simply connected ESP32 to the MQTT server. This is just one of the more basic capabilities of ESP32. In fact, ESP32 can connect to various iot sensors and report sensor data to the MQTT server.

We will be publishing more articles on the development of the Internet of Things and ESP32, so stay tuned.

Copyright notice: this article is the original EMQ, reprint please indicate the source.

The original link: https://www.emqx.com/zh/blog/esp32-connects-to-the-free-public-mqtt-broker