In this example we will connect to an MQTT topic, I used a Wemos Lolin32 – you can use any ESP32 development board
We used cloudmqtt which has a free option and then create an instance, you would see something like this
Code
In this example you need to install the PubSubClient which make the task easier, you can do this through the library manager, if you want to find out more then visit https://pubsubclient.knolleary.net/
The first part of the code deals with wifi connection and CloudMQTT settings
const char* ssid = “wifi username”;
const char* password = “wifi password”;
const char* mqttServer = “mqtt server”;
const int mqttPort = mqtt port;
const char* mqttUser = “mqtt username”;
const char* mqttPassword = “mqtt password”;
Now if we click on the instance that we created you can find the information you need to enter for the MQTT server
i have removed the username and password from the image below but this will give you an idea of what you will see
Here is the complete code example
[cpp]
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = “wifi username”;
const char* password = “wifi password”;
const char* mqttServer = “mqtt server”;
const int mqttPort = mqtt port;
const char* mqttUser = “mqtt username”;
const char* mqttPassword = “mqtt password”;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println(“Connecting to WiFi..”);
}
Serial.println(“Connected to the WiFi network”);
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println(“Connecting to MQTT…”);
if (client.connect(“ESP32Client”, mqttUser, mqttPassword )) {
Serial.println(“connected”);
} else {
Serial.print(“failed with state “);
Serial.print(client.state());
delay(2000);
}
}
client.publish(“esp32/esp32test”, “Hello from ESP32learning”);
}
void loop() {
client.loop();
}
[/cpp]
Open the serial monitor and you should see something like the following
Connecting to WiFi..
Connecting to WiFi..
Connected to the WiFi network
Connecting to MQTT…
connected
To test this quickly and easily I use MQTTLens in Chrome, you can see in the screen capture below I subscribed to esp32/esp32test and you can also see messages coming through