Subscribing to MQTT topic using an ESP32

In this example we will subscribe to an MQTT broker and topic.

Again we use the same CloudMQtt, arduino libraries and MQTTlens chrome app that we used in the previous example

This is mainly a code example

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”;


#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "wifi username";
const char* password = "wifi password";
const char* mqttServer = "m20.cloudmqtt.com";
const int mqttPort = 17914;
const char* mqttUser = "penfkmby";
const char* mqttPassword = "R2C9F3SvwAGS";

WiFiClient espClient;
PubSubClient client(espClient);

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 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);
client.setCallback(callback);

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.subscribe("esp32/esp32test");

}

void loop()
{
client.loop();
}

Testing

You will need to open the Serial monitor to see any messages sent from the topic, in MQTTlens you will have to publish to the correct topic

In the screen capture below I have tried to show this, I have sent the messages and the Arduino serial monitor is displaying them as they arrive