# 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 (opens new window) 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 (opens new window) provided by EMQX. This service was created based on the EMQX Cloud (opens new window). 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 (opens new window) 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:
- Install ESP8266 development board. Click Tools -> Development Board -> Development Board Management. Search ESP8266 and click Install.
- 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.
- Import libraries ESP8266WiFi and PubSubClient.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
2
- 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 Auth to set username and password.
// 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
2
3
4
5
6
7
8
9
10
- Open a serial connection to output the result of the program and connect to the Wi-Fi network.
// 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..");
}
2
3
4
5
6
7
8
- Set MQTT broker, write callback function, and print connection information on the serial monitor at the same time.
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);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
- After successfully connecting to the MQTT broker, ESP8266 will publish messages on topic
esp8266/test
to the MQTT server and subscribe to messages on topicesp8266/test
.
// publish and subscribe
client.publish(topic, "hello emqx"); // publish to the topic
client.subscribe(topic); // subscribe from the topic
2
3
- Print the topic name to the serial port and then print every byte of received messages.
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("-----------------------");
}
2
3
4
5
6
7
8
9
10
The complete code is displayed as follows:
#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();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 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.
- Import libraries ESP8266WiFi and PubSubClient.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecureBearSSL.h>
2
3
- 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 Auth to set username and password.
// 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
2
3
4
5
6
7
8
9
10
- 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.
// 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";
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- Open a serial connection to output the result of the program and connect to the Wi-Fi network.
// 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");
2
3
4
5
6
7
8
9
- Set fingerprint and MQTT broker. Write callback function, and print connection information on the serial monitor at the same time.
// 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);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- After successfully connecting to the MQTT broker, ESP8266 will publish messages and subscribe to the MQTT broker.
// publish and subscribe
client.publish(topic, "hello emqx"); // publish to the topic
client.subscribe(topic); // subscribe from the topic
2
3
- Print the topic name to the serial port and then print every byte of received messages.
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("-----------------------");
}
2
3
4
5
6
7
8
9
10
The complete code is displayed as follows:
#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();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 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.
- Use Arduino IDE to upload the complete code to ESP8266 and open the serial monitor.
- Establish the connection between MQTTX client and MQTT broker, and send messages to ESP8266.
- View the messages ESP8266 received in the serial monitor.
# 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 (opens new window), and you can also find more demo examples in other languages on GitHub (opens new window).