ESP8266 connects to MQTT broker with Arduino

MQTT is a lightweight and flexible protocol to exchange IoT messages and deliver data. It dedicates to achieve 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 EMQ X MQTT Cloud, and programming ESP8266 by using Arduino IDE. EMQ X 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
  • MQTT X: 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 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 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. Printing 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 MQTT X client and 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 EMQ X 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.

We will release more articles related to IoT development and ESP8266. Stay tuned.

Did you like this blog post? Share it now

Related Posts

Remote control LED with ESP8266 and MQTT

In this project, we will implement remote control LED lights via NodeMCU(ESP8266) and MQTT broker, and use the Arduino IDE to program NodeMCU ESP8266.

Dekun Tao 2021-03-25
Integrate EMQ X MQTT Cloud with Home Assistant

In this article, we will introduce to you the process of integrating Home Assistant with EMQ X MQTT Cloud, a Cloud-Native fully managed MQTT service.

Upload sensor data to MQTT cloud service via NodeMCU (ESP8266)

This example will demonstrate how to report the temperature and humidity data collected by the DHT11 sensor to the MQTT service in the cloud through the MQTT protocol and the NodeMCU based on ESP8266 , and show how the application subscribes to and processes the data.

2019-12-03