3

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.

ESP32 is an upgraded version of ESP8266. In addition to the Wi-Fi module, this module also includes a Bluetooth 4.0 module. The dual-core CPU operates at a frequency of 80 to 240 MHz, contains two Wi-Fi and Bluetooth modules and various input and output pins. ESP32 is an ideal choice for IoT projects.

In this project we will achieve ESP32 connected to the X-EMQ MQTT Cloud operation and maintenance of free public MQTT server , and use the Arduino IDE to program ESP32. EMQ X Cloud is EMQ . It provides one-stop operation and maintenance management and a unique isolation environment MQTT 5.0 access service.

Required IoT components

Arduino configuration

Install ESP32 development board

Click Tools -> Development Board -> Development Board Management -> Search ESP32 -> Click Install

安装 ESP32 开发板

Install PubSub client

Project -> Load Library -> Manage Library... -> Search PubSubClient -> Install PubSubClient by Nick O'Leary

安装 PubSub client

ESP32 Pub/Sub diagram

ESP32 Pub/Sub 示意图

ESP32 code writing

Connect MQTT step by step

  1. First, we will import WiFi and PubSubClient libraries, ESP8266WiFi library can connect ESP32 to Wi-Fi network, PubSubClient library can connect ESP32 to MQTT server to publish messages and subscribe 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 is the topic "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 in order to output the results of the program and connect 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. 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. After the MQTT server is successfully connected, ESP32 will 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 message received esp32/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("-----------------------");
    }

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. Use Arduino to upload the complete code and power on the esp32
  2. Open the serial monitor, select 115200 baud rate, and check the connection status of ESP32

    查看 ESP32 连接情况

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

    使用 MQTT X 客户端向 ESP32 发送消息

Summarize

So far, we have successfully connected to the public MQTT server provided by EMQ X Cloud 160fa7710dffda. In this project, we simply connect ESP32 to the MQTT server. This is just one of the basic capabilities of ESP32. ESP32 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 ESP32, so stay tuned.

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

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


EMQX
336 声望437 粉丝

EMQ(杭州映云科技有限公司)是一家开源物联网数据基础设施软件供应商,交付全球领先的开源 MQTT 消息服务器和流处理数据库,提供基于云原生+边缘计算技术的一站式解决方案,实现企业云边端实时数据连接、移动、...