ESP8266 Connects to MQTT Broker with Arduino

MQTT is a lightweight and flexible protocol to exchange IoT messages and deliver data. It dedicates to achieving a balance between flexibility and hardware/network resources for the IoT developer.
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.
In this project, we will implement connecting ESP8266 to free public MQTT broker operated and maintained by EMQX Cloud, and programming ESP8266 by using Arduino IDE. EMQX Cloud is an MQTT IoT cloud service platform with security launched by EMQ. It provides a one-stop operation and maintenance agency and MQTT 5.0 access service with a uniquely isolated environment.
The Required IoT Components
- ESP8266
- Arduino IDE
- MQTTX: Cross-platform MQTT 5.0 client tool
- The free public MQTT broker
- Broker: broker.emqx.io
- TCP Port: 1883
- Websocket Port: 8083
ESP8266 Pub/Sub
The code
Firstly, we import libraries ESP8266WiFi and PubSubClient. ESP8266WiFi library can connect ESP8266 to the Wi-Fi network, PubSubClient library can enable ESP8266 to connect to the MQTT broker for publishing messages and subscribing topics.
#include <ESP8266WiFi.h> #include <PubSubClient.h>
Set Wi-Fi name and password, and connection address and port of MQTT broker
// 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"; const char *topic = "esp8266/test"; const char *mqtt_username = "emqx"; const char *mqtt_password = "public"; const int mqtt_port = 1883;
Open a serial connection for facilitating to output of the result of the program and connecting 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.."); }
Set MQTT broker, write the 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); } } 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("-----------------------"); }
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"); client.subscribe(topic);
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("-----------------------"); }
The full code
#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"; const char *topic = "esp8266/test"; const char *mqtt_username = "emqx"; const char *mqtt_password = "public"; const int mqtt_port = 1883; 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"); client.subscribe(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(); }
Run and Test
Please use Arduino IDE to upload the complete code to ESP8266 and open the serial monitor
Establish the connection between the MQTTX client and the MQTT broker, and send messages to ESP8266
View the messages ESP8266 received in the serial monitor
Summary
So far, we have successfully connected ESP8266 to the free public MQTT broker provided by EMQX Cloud. In this project, we connect ESP8266 to the MQTT broker, which is one of the relatively basic capabilities of ESP8266. Besides that, ESP8266 can also connect to various IoT sensors, and report the sensor data to the MQTT broker.
Next, you can check out The Easy-to-understand Guide to MQTT Protocol series of articles provided by EMQ to learn about MQTT protocol features, explore more advanced applications of MQTT, and get started with MQTT application and service development.
Resources
- MQTT on ESP32: A Beginner's Guide
- How to Use MQTT on Raspberry Pi with Paho Python Client
- MicroPython MQTT Tutorial Based on Raspberry Pi
- Remote control LED with ESP8266 and MQTT
- Upload Sensor Data to MQTT Cloud Service via NodeMCU (ESP8266)