Tutorial: https://www.emqx.com/en/blog/esp32-connects-to-the-free-public-mqtt-broker
Exemplo
Usando a lib PubSubClient
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi
const char *ssid = "wifi-ssid"; // Enter your Wi-Fi name
const char *password = "mywifipassword#"; // Enter Wi-Fi password
// MQTT Broker
const char *mqtt_broker = "broker-host-or-ip";
const char *topic = "topicname";
const char *mqtt_username = "username";
const char *mqtt_password = "password";
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 Wi-Fi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
ensureConnection();
client.publish(topic, "Hi, I'm ESP32 ^^");
}
void ensureConnection() {
if (client.connected()) {
return;
}
while (!client.connected()) {
Serial.println("Not 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);
}
}
client.setCallback(callback);
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() {
ensureConnection();
client.loop();
}