Wednesday , December 11 2019

MQTT Subscriber in ESP328266 using Arduino

Before going to start any coding. First we will talk about the Arduino environment setup.

Firstly, you can download the Arduino setup from here: https://www.arduino.cc/en/main/software

After this now you can configure the Arduino environment for ESP328266

Open the preference setting

Now, you can add the json link into below given section.
http://arduino.esp8266.com/stable/package_esp8266com_index.json
This link allows you to install the library for ESP32 Modules.

After this, you need to setup the Board Manager for the ESP328266 Module.

Type ESP in the Board Search menu to get the information about these Board.

Simply, install the board driver as and your Board setup environment for esp328266 is finished.

Further, you will configure you COM Port which is generally different in every case. First you need to confirm which is your port of esp328266. By just plug and unplug into USB port.

In last, you can set your board on this configuration otherwise you should have a problem to upload the code into the esp328266.

This is all about the how to configure your Arduino environment for esp328266.

For MQTT using in ESP328266 you need to install the library name “PUBSUBCLIENT”

There are too many PubSubClient Libraries. But, you can install only that is installed in the given below section.

Finally, now we setup all the environments for each and everything. Lets talk about the business. Means the real code.


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

// Update these with values suitable for your network.

const char* ssid = "<username>";
const char* password = "<password>";
const char* mqtt_server = "<mqtt-server-name/ip>";

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.subscribe("onoff");
    } 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() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

This code blink your Builtin LED on your ESP328266 module. Also it will shows the message of your entire publisher topic. I use the same topic which I was declared in the MOSCA server example. So, need to use the Serial Monitor to get this.

About Faheem

Faheem
An adaptable and responsible Software Engineer, who enjoys working with computers and the opportunity to learn new skills and work with new technologies is particularly attractive to me.

Check Also

MOSCA MQTT Server Using Node JS

Before we going to start something. We should know about what is the MQTT server …

Leave a Reply

Your email address will not be published.