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
- ESP32
- Arduino IDE
- MQTT 5.0 Client Tool-MQTT X
Deployed in EMQ the X-Cloud free public on the MQTT server
- Broker: broker-cn.emqx.io
- TCP Port: 1883
- Websocket Port: 8083
Arduino configuration
Install ESP32 development board
Click Tools -> Development Board -> Development Board Management -> Search ESP32 -> Click Install
Install PubSub client
Project -> Load Library -> Manage Library... -> Search PubSubClient -> Install PubSubClient by Nick O'Leary
ESP32 Pub/Sub diagram
ESP32 code writing
Connect MQTT step by step
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>
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;
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.."); }
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); } }
After the MQTT server is successfully connected, ESP32 will
esp/test
and subscribe toesp/test
topic messages.// publish and subscribe client.publish(topic, "Hi EMQ X I'm ESP32 ^^"); client.subscribe(topic);
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
- Use Arduino to upload the complete code and power on the esp32
Open the serial monitor, select 115200 baud rate, and check the connection status of ESP32
Use MQTT X client to connect to a public MQTT server and send messages to 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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。