ESP8266 MQTT Tutorial: How to Use MQTT for IoT Messaging

Difficulty Level: Intermediate

In this tutorial, you’ll learn how to use MQTT for IoT messaging, enabling an ESP8266 to send data to an MQTT broker and subscribe to receive messages. MQTT (Message Queuing Telemetry Transport) is a lightweight protocol perfect for IoT applications.

Components Required

System Overview

The ESP8266 will publish sensor data (e.g., temperature readings) to an MQTT broker at regular intervals. Any device subscribing to the topic will receive the published data. Similarly, you can send control commands to the ESP8266 via the broker to perform actions (e.g., turning on an LED).

Setting Up the MQTT Broker

You can either install Mosquitto locally or use a cloud service like HiveMQ Cloud for the MQTT broker. The broker will manage message distribution between the ESP8266 (publisher) and any subscribers (e.g., mobile apps or other devices).

Cloud MQTT Broker Setup

If using HiveMQ Cloud, create an account and generate a unique broker address, username, and password. You will use this information to connect the ESP8266 to the broker.

Wiring the ESP8266

If using a sensor (e.g., DHT11 for temperature), wire it to the ESP8266:

Arduino Code

Below is the code to set up MQTT communication on the ESP8266:


// Required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// WiFi and MQTT Broker details
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
const char* mqtt_broker = "broker.hivemq.com";
const char* topic = "esp/test";
const char* mqtt_username = "Your_Username";
const char* mqtt_password = "Your_Password";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  // Connect to WiFi
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);

  // Connect to MQTT broker
  while (!client.connected()) {
    String client_id = "esp8266-client-";
    client_id += String(WiFi.macAddress());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("Connected to MQTT broker");
      client.subscribe(topic);  // Subscribe to a topic
    } else {
      delay(2000);
    }
  }
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message received from topic: ");
  Serial.println(topic);
  String msg;
  for (int i = 0; i < length; i++) {
    msg += (char)message[i];
  }
  Serial.println("Message: " + msg);
  // Add code to control devices based on received message
}

void loop() {
  client.loop();
  
  // Publish sensor data
  String data = "Hello from ESP8266";
  client.publish(topic, data.c_str());
  
  delay(5000);  // Publish every 5 seconds
}
        

Code Explanation

Testing the System

  1. Upload the code to the ESP8266.
  2. Monitor the serial output to see if the ESP successfully connects to WiFi and the MQTT broker.
  3. Use an MQTT client (e.g., MQTT Explorer, or another ESP) to subscribe to the topic esp/test to receive published messages.
  4. Send messages to the ESP via the MQTT broker to test device control through the callback() function.

Conclusion

You've now set up basic MQTT communication with the ESP8266. The ESP can publish sensor data to the broker, and you can send control commands back to the ESP from any subscribed device. This setup is essential for building IoT systems where multiple devices communicate seamlessly.