Skip to content
On this page

Connect with ESP8266

This article mainly introduces how to use PubSubClient in the ESP8266 project, including implementing the connection, subscription, messaging, and other functions between the client and MQTT broker.

ESP8266 provides a highly integrated Wi-Fi SoC solution. Its low-power, compact design, and high stability can meet user's requirements. ESP8266 has a complete and self-contained Wi-Fi network function, which can be applied independently or can run as a slave at another host MCU.

This article demonstrates how to connect an ESP8266 client to MQTT broker via the TCP port and TLS/SSL port respectively. For Serverless deployments, see the demonstration on TLS/SSL port connection. Settings for connections over TCP port are different from those for connections over TLS/SSL port, but the code used in the publishing and subscribing functions is the same.

Prerequisites

Before the connection, you need to get the broker and client ready.

Get MQTT Broker

You can use the free public MQTT broker provided by EMQX. This service was created based on the EMQX Cloud. The information about broker access is as follows:

  • Broker: broker.emqx.io
  • TCP Port: 1883
  • SSL/TLS Port: 8883

You can create a deployment as well. Find connection information in deployment overview. Make sure the deployment is running. Use the TCP port or TLS/SSL port to test the connection to the MQTT server.

If you are creating your own deployment, check Authentication and set the username and password in Authentication & ACL > Authentication for verification.

Arduino IDE

This article uses the Arduino IDE as the code editor and uploader. The open-source Arduino Software (IDE) makes it easy to write code and upload it to the board. This software can be used with any Arduino board.

Installation Dependencies

In Arduino IDE, complete the following installations:

  1. Install ESP8266 development board. Click Tools -> Development Board -> Development Board Management. Search ESP8266 and click Install.
  2. Install PubSub client. ClickProject -> Load library -> Library manager.... Search PubSubClient and Install PubSubClient by Nick O’Leary.

Connect over TCP Port

This section describes how to connect an ESP8266 client to MQTT broker over TCP port in Arduino IDE.

  1. Import libraries ESP8266WiFi and PubSubClient.
c
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
  1. Set Wi-Fi name and password, and connection address and port.

The sample code will use a public MQTT server to connect, and the public MQTT server does not require a username and password. If you create a deployment, please refer to Serverless Auth or Dedicated / BYOC Auth to set username and password.

c
// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io"; // broker address
const char *topic = "esp8266/test"; // define topic 
const char *mqtt_username = "emqx"; // username for authentication
const char *mqtt_password = "public"; // password for authentication
const int mqtt_port = 1883; // port of MQTT over TCP
  1. Open a serial connection to output the result of the program and connect to the Wi-Fi network.
c
// 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..");
}
  1. Set MQTT broker, write callback function, and print connection information on the serial monitor at the same time.
c
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
    String client_id = "esp8266-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)) {
    } else {
        Serial.print("failed with state ");
        Serial.print(client.state());
        delay(2000);
    }
}
  1. After successfully connecting to the MQTT broker, ESP8266 will publish messages on topic esp8266/test to the MQTT server and subscribe to messages on topic esp8266/test.
c
// publish and subscribe
client.publish(topic, "hello emqx"); // publish to the topic
client.subscribe(topic); // subscribe from the topic
  1. Print the topic name to the serial port and then print every byte of received messages.
c
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("-----------------------");
}

The complete code is displayed as follows:

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

// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io"; // broker address
const char *topic = "esp8266/test"; // define topic 
const char *mqtt_username = "emqx"; // username for authentication
const char *mqtt_password = "public"; // password for authentication
const int mqtt_port = 1883; // port of MQTT over TCP

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 WiFi network");
  //connecting to a mqtt broker
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
      String client_id = "esp8266-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);
      }
  }
  // publish and subscribe
  client.publish(topic, "hello emqx"); // publish to the topic
  client.subscribe(topic); // subscribe from the 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() {
  client.loop();
}

Connect over TLS/SSL Port

This section describes how to connect an ESP8266 client to MQTT broker over TLS/SSL port in Arduino IDE. Settings for connections over TLS/SSL ports are different from those for connections over TCP port, but the code is the same in the publishing and subscribing functions.

  1. Import libraries ESP8266WiFi and PubSubClient.
c
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecureBearSSL.h>
  1. Set Wi-Fi name and password, and connection address and port.

The sample code will use a public MQTT server to connect, and the public MQTT server does not require a username and password. If you create a deployment, please refer to Serverless Auth or Dedicated / BYOC Auth to set username and password.

c
// WiFi
const char *ssid = "[WIFI SSID]"; // Enter your WiFi name
const char *password = "[WIFI password]";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io"; // broker address
const char *topic = "esp8266/test"; // define topic 
const char *mqtt_username = "emqx"; // username for authentication
const char *mqtt_password = "public"; // password for authentication
const int mqtt_port = 8883; // port of MQTT over TLS/SSL
  1. Set fingerprint The fingerprints of EMQX broker, for reference only. If you are not using EMQX Cloud Serverless or public EMQX broker, you need to calculate the sha1 fingerprint of your server certificate and update the 'fingerprint' variable below.
c
// init wifi client
WiFiClientSecure espClient;
PubSubClient client(espClient);

/*
  The common fingerprints of EMQX broker, for reference only.
  If you are not using EMQX Cloud Serverless or public EMQX broker,
  you need to calculate the sha1 fingerprint of your server certificate
  and update the 'fingerprint' variable below.
*/
// 1. fingerprint of public emqx broker. Host: broker.emqx.io
const char* fingerprint = "B6 C6 FF 82 C6 59 09 BB D6 39 80 7F E7 BC 10 C9 19 C8 21 8E";
// 2. fingerprint of EMQX Cloud Serverless. Host: *.emqxsl.com
// const char* fingerprint = "42:AE:D8:A3:42:F1:C4:1F:CD:64:9C:D7:4B:A1:EE:5B:5E:D7:E2:B5";
// 3. fingerprint of EMQX Cloud Serverless. Host: *.emqxsl.cn
// const char* fingerprint = "7E:52:D3:84:48:3C:5A:9F:A4:39:9A:8B:27:01:B1:F8:C6:AD:D4:47";
  1. Open a serial connection to output the result of the program and connect to the Wi-Fi network.
c
// 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 WiFi network");
  1. Set fingerprint and MQTT broker. Write callback function, and print connection information on the serial monitor at the same time.
c
// set fingerprint
espClient.setFingerprint(fingerprint);
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
    String client_id = "esp8266-client-";
    client_id += String(WiFi.macAddress());
    Serial.printf("The client %s connects to the mqtt broker\n", client_id.c_str());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
        Serial.println("Connected to MQTT broker.");
    } else {
        Serial.print("Failed to connect to MQTT broker, rc=");
        Serial.print(client.state());
        Serial.println(" Retrying in 5 seconds.");
        delay(5000);
    }
}
  1. After successfully connecting to the MQTT broker, ESP8266 will publish messages and subscribe to the MQTT broker.
c
// publish and subscribe
client.publish(topic, "hello emqx"); // publish to the topic
client.subscribe(topic); // subscribe from the topic
  1. Print the topic name to the serial port and then print every byte of received messages.
c
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("-----------------------");
}

The complete code is displayed as follows:

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

// WiFi
const char *ssid = "[WIFI SSID]"; // Enter your WiFi name
const char *password = "[WIFI password]";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io"; // broker address
const char *topic = "esp8266/test"; // define topic 
const char *mqtt_username = "emqx"; // username for authentication
const char *mqtt_password = "public"; // password for authentication
const int mqtt_port = 8883; // port of MQTT over TLS/SSL

// init wifi client
WiFiClientSecure espClient;
PubSubClient client(espClient);

/*
  The common fingerprints of EMQX broker, for reference only.
  If you are not using EMQX Cloud Serverless or public EMQX broker,
  you need to calculate the sha1 fingerprint of your server certificate
  and update the 'fingerprint' variable below.
*/
// 1. fingerprint of public emqx broker. Host: broker.emqx.io
const char* fingerprint = "B6 C6 FF 82 C6 59 09 BB D6 39 80 7F E7 BC 10 C9 19 C8 21 8E";
// 2. fingerprint of EMQX Cloud Serverless. Host: *.emqxsl.com
// const char* fingerprint = "42:AE:D8:A3:42:F1:C4:1F:CD:64:9C:D7:4B:A1:EE:5B:5E:D7:E2:B5";
// 3. fingerprint of EMQX Cloud Serverless. Host: *.emqxsl.cn
// const char* fingerprint = "7E:52:D3:84:48:3C:5A:9F:A4:39:9A:8B:27:01:B1:F8:C6:AD:D4:47";


void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to the WiFi network");

  // set fingerprint
  espClient.setFingerprint(fingerprint);
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
    String client_id = "esp8266-client-";
    client_id += String(WiFi.macAddress());
    Serial.printf("The client %s connects to the mqtt broker\n", client_id.c_str());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
        Serial.println("Connected to MQTT broker.");
    } else {
        Serial.print("Failed to connect to MQTT broker, rc=");
        Serial.print(client.state());
        Serial.println(" Retrying in 5 seconds.");
        delay(5000);
    }
  }

    // publish and subscribe
    client.publish(topic, "hello emqx"); // publish to the topic
    client.subscribe(topic); // subscribe from the 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() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

Test Connection

After the ESP8266 client has successfully connected to the MQTT broker, you can use the Arduino IDE and MQTTX to test the connection.

  1. Use Arduino IDE to upload the complete code to ESP8266 and open the serial monitor. esp8266_connection
  2. Establish the connection between MQTTX client and MQTT broker, and send messages to ESP8266. esp8266_mqttx
  3. View the messages ESP8266 received in the serial monitor. esp8266_receive

More

In summary, we have implemented the creation of an MQTT connection in an ESP8266 project, and simulated connecting, subscribing, sending and receiving messages between the client and MQTT broker. You can download the source code of the example here, and you can also find more demo examples in other languages on GitHub.