Firstly to use MQTT with the esp8266 you will need to install the “pubsubclient” library from the library manager. (See Image Below)

Once the library is installed be sure to include the library in your Arduino sketch.

#include <PubSubClient.h>

You will also need the general wifi/ethernet library so that it has an internet connection.

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Ethernet.h>

we will also need to declare our MQTT Client objects like so.

WiFiClient espClient;
ESP8266WiFiMulti WiFiMulti;
PubSubClient client(espClient);

In our setup() we will need to let the MQTT Client know where the broker is at and set up our callback for our subscribed topics.

void setup()
{
  Serial.begin(57600);
  //TO SEE YOUR MQTT MESSAGES VIEW THE SERIAL MONITOR

  client.setServer(server, 1883);
  client.setCallback(callback);
  
  delay(1500);
}

We now need to setup a reconnect function so that we can initialise connecting to the broker, while at the same time catching any disconnects and attempting to reconnect. Inside this function we will also setup our topics we want to subscribe to as we can guarantee we will have a connection to the broker by this point.

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient")) {
      Serial.println("connected");
      // Once connected, publish an announcement...

      // THIS IS WHERE WE SUBSRIBE TO ANY TOPICS, ONCE WE HAVE A CONNECTION
      client.subscribe("yourtopic");


    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

Now we need to setup our main loop to incorporate our reconnect function, as well as connecting to the wifi and ensuring we will reconnect if a disconnect were to happen.

void loop()
{

  
  if (WiFi.status() != WL_CONNECTED) {
      Serial.print("Wait for WiFi... ");
    
      while (WiFiMulti.run() != WL_CONNECTED) {
         Serial.print(".");
         delay(500);
      }
    
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

  }
  
  if (WiFi.status() == WL_CONNECTED) {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
  }


  
}

This loop will check to see if the client is not connected and then attempt to reconnect to the broker.

Lastly we need to setup our callback function for our subscribed topics

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

Once we have all this in a single Arduino sketch we will have a fully functioning MQTT Client on the esp8266..

Here is the full code for your reference

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <PubSubClient.h>


WiFiClient espClient;
ESP8266WiFiMulti WiFiMulti;
PubSubClient client(espClient);


void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClientName")) {
      Serial.println("connected");
      // Once connected, publish an announcement...

      // THIS IS WHERE WE SUBSRIBE TO ANY TOPICS, ONCE WE HAVE A CONNECTION
      client.subscribe("yourtopic");


    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup()
{
  Serial.begin(57600);
  //TO SEE YOUR MQTT MESSAGES VIEW THE SERIAL MONITOR

  client.setServer("YOUR MQTT BROKER", 1883);
  client.setCallback(callback);
  
  delay(1500);
}

void loop()
{

  
  if (WiFi.status() != WL_CONNECTED) {
      Serial.print("Wait for WiFi... ");
    
      while (WiFiMulti.run() != WL_CONNECTED) {
         Serial.print(".");
         delay(500);
      }
    
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

  }
  
  if (WiFi.status() == WL_CONNECTED) {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
  }


  
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *