EMQX Dedicated New Feature: Event History is available for private beta test. →

ESP8266 Connects to MQTT Broker with Arduino

Dekun Tao
May 22, 2020
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

project.png

The code

  1. 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>
    
  2. 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;
    
  3. 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..");
    }
    
  4. 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("-----------------------");
    }
    
  5. 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);
    
  6. 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("-----------------------");
    }
    
  7. 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

  1. Please use Arduino IDE to upload the complete code to ESP8266 and open the serial monitor

    esp_con.png

  2. Establish the connection between the MQTTX client and the MQTT broker, and send messages to ESP8266

    mqttx_pub.png

  3. View the messages ESP8266 received in the serial monitor

    esp_msg.png

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

Try EMQX Cloud for Free
No credit card required
Get Started →

Related Posts

Jun 10, 2023Dekun Tao
MQTT on ESP32: A Beginner's Guide

This blog will show you the process of publishing MQTT messages and topic subscription on ESP32 using Arduino IDE through a simple demo.

Jun 3, 2023Saiteng You
How to Use MQTT on Raspberry Pi with Paho Python Client

The Paho Python Client provides a client class with support for both MQTT v3.1 and v3.1.1 on Python 2.7 or 3.x. This article introduces how to use the Paho MQTT client library in the Python project.

Mar 14, 2024Dekun Tao
Remotely Control an LED with ESP8266 and MQTT

This blog will use the ESP8266 as the publisher to send messages to a topic, which a subscriber will listen to, allowing us to control the on/off state of an LED light remotely.