yahboom
HomeLearn
Solution
Blog
Online Store
About Us
EN/中文
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

Welcome to ESP32 Core Board repository

10. MQTT IoT Communication Protocol

MQTT IoT Communication Protocol


MQTT IoT Communication Protocol1. MQTT Overview2. Core Concepts2.1 Publish/Subscribe Model2.2 QoS Message Quality Levels2.3 Key Role of client.loop()3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Explanation5.1 Configuration and Global Variables5.2 Message Callback5.3 Reconnection and Subscription5.4 loop() — MQTT Main Loop6. Operation Flow6.1 Build and Flash6.2 Operation Steps6.3 Verification Methods7. Common Problems


1. MQTT Overview

MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe messaging protocol designed specifically for IoT. All communication is relayed through a Broker, completely decoupling publishers and subscribers. This experiment connects to the public Broker broker.emqx.io, subscribes to the esp32/sub topic to receive messages, and publishes messages to esp32/pub topic every 3 seconds.

Typical Application Scenarios:

Application TypeExample
Sensor Data ReportingTemperature/humidity published to cloud platform regularly
Remote ControlMobile app publishes "turn on light" message, device subscribes to same topic
Smart HomeMultiple devices work together through the same Broker
Industrial IoTPLC status monitoring, production line data collection

2. Core Concepts

2.1 Publish/Subscribe Model

Publisher ──PUBLISH("esp32/temp", "25℃")──→ Broker ──forward──→ Subscriber
                                                  ──forward──→ Subscriber

Publishers and subscribers do not connect directly; they match through Topics. Topics are separated by /, such as home/livingroom/temperature. Wildcard subscriptions: + matches a single level, # matches all remaining levels.

2.2 QoS Message Quality Levels

QoSMeaningConfirmation Mechanism
0At most onceFire and forget, no confirmation
1At least oncePUBACK confirmation + retransmission, may duplicate
2Exactly onceFour-way handshake, guaranteed no loss or duplication

2.3 Key Role of client.loop()

client.loop() must be called frequently in loop(). Internally it handles: checking and parsing MQTT packets received from Broker → calling callback() for PUBLISH packets → automatically sending PINGREQ to maintain Keep Alive → handling QoS 1/2 acknowledgment retransmission.


3. Hardware Dependencies

Pure software experiment. Requires connecting to router via WIFI-STA first, and the router must have internet access (experiment uses public Broker broker.emqx.io).

DependencyDescription
Network ConnectionWiFi 2.4GHz, WIFI-STA mode, router must have internet access
Protocol StackTCP/IP (lwIP), MQTT based on TCP connection (port 1883)
Flash UsagePubSubClient library approximately 30KB, no problem for ESP32-S3
Bandwidth RequirementExtremely low, Keep Alive heartbeat only 2 bytes, PUBLISH packet is dozens of bytes
RAM RequirementPubSubClient default buffer 256 bytes (MQTT_MAX_PACKET_SIZE), can be increased in library header file
Library DependencyPubSubClient by Nick O'Leary (search and install in Arduino IDE library manager)
Brokerbroker.emqx.io:1883 (EMQX public test Broker, no registration required)

MQTT is specifically designed for low bandwidth, low power, unreliable networks. Protocol header is minimum only 2 bytes, supports QoS level confirmation and will message, very suitable for NB-IoT, LoRa gateway behind narrowband links and battery-powered sensor nodes.


4. Project Architecture and Flow

​x
setup()
  ├─ connectWiFi()
  ├─ client.setServer(broker, 1883)    // Set Broker address
  └─ client.setCallback(callback)      // Register message callback

loop()
  ├─ if not connected → reconnect()    // CONNECT + SUBSCRIBE
  ├─ client.loop()                     // Handle receive + maintain heartbeat
  └─ every 3 seconds: client.publish(topic, msg)

5. Source Code Explanation

Complete source code: Source code → Arduino → 3.Network Communication → MQTT → MQTT.ino

5.1 Configuration and Global Variables

PubSubClient must be bound to a WiFiClient instance, so create WiFiClient first then create PubSubClient. MQTT default port 1883 (unencrypted), encrypted MQTT uses 8883.

xxxxxxxxxx
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);          // MQTT over TCP

const char* MQTT_SERVER = "broker.emqx.io";
const int   MQTT_PORT   = 1883;
const char* TOPIC_SUB   = "esp32/sub";
const char* TOPIC_PUB   = "esp32/pub";

5.2 Message Callback

When receiving a PUBLISH packet for a subscribed topic from the Broker, client.loop() calls this function. payload is not guaranteed to be null-terminated, must use length parameter to limit read range.

xxxxxxxxxx
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.printf("Received [%s]: ", topic);
  for (int i = 0; i < length; i++)
    Serial.print((char)payload[i]);
  Serial.println();
}

5.3 Reconnection and Subscription

Automatically reconnect after losing connection, re-subscribe after successful reconnection (Broker does not remember subscription relationships by default).

xxxxxxxxxx
void reconnect() {
  while (!client.connected()) {
    if (client.connect("MQTT_Client")) {   // Send CONNECT packet
      Serial.println("MQTT Connected!");
      client.subscribe(TOPIC_SUB);          // Re-subscribe
    } else {
      Serial.printf("Failed, rc=%d retry in 5s\n", client.state());
      delay(5000);
    }
  }
}

client.state() returns disconnection reason: -4 connection timeout, 2 Client ID rejected, 4 username/password error, etc.

5.4 loop() — MQTT Main Loop

loop() does three things: check connection (reconnect if disconnected), call client.loop() to handle packet reception and heartbeat, publish a message to esp32/pub every 3 seconds.

xxxxxxxxxx
void loop() {
  if (!client.connected()) reconnect();
  client.loop();   // Handle receive + maintain Keep Alive

  static unsigned long last = 0;
  if (millis() - last > 3000) {
    last = millis();
    client.publish(TOPIC_PUB, "Hello MQTT from ESP32-S3");
  }
}

6. Operation Flow

6.1 Build and Flash

Arduino flash flow: See Arduino → 1. Before Development → 2. Build and Flash.

  1. Install library: Arduino IDE → Library Manager → Search "PubSubClient" → Install

  2. Build and flash

6.2 Operation Steps

Step 1: Install PubSubClient Library

Arduino IDE → Sketch → Include Library → Manage Libraries → Search PubSubClient → Install (author Nick O'Leary).

Open Library

Install Library

Step 2: Build and Flash, Open Serial Monitor

Build and flash to ESP32-S3 development board. Open serial monitor (baud rate 115200), wait for WiFi connection success, ESP32 automatically connects to public Broker and subscribes to esp32/sub topic:

xxxxxxxxxx
MQTT Connected!
Sent: Hello MQTT from ESP32-S3

Serial port prints a Sent: message every 3 seconds, indicating the publish channel is working.

Step 3: Verify Bidirectional Communication with MQTTX

Open MQTTX client on PCMQTTX example, configure and connect with the following parameters:

MQTTX Settings

ParameterValue
Brokerbroker.emqx.io
Port1883
Client IDArbitrary (e.g., PC_Client)

MQTTX Interface Overview

  1. Create Publish: Click (New Subscription) on the MQTT server side - server subscription == client publish

    Create Publish 1

    Select publish topic: (example: esp32/pub), select service level (QoS 0)

     

    Create Publish 2

     

  2. Create Subscription: Click to input the server's publish topic (client's subscription topic): esp32/sub, service level is also QoS 0.

    Create Subscription

  3. Verify Publish: After MQTTX is connected to the same Broker, subscribe to esp32/pub topic, should receive Hello MQTT from ESP32-S3 sent by ESP32 every 3 seconds

    mqtt serial interaction

  4. Verify Subscription: Send Hello from MQTTX to esp32/sub topic in MQTTX, ESP32 serial monitor prints:

xxxxxxxxxx
Received [esp32/sub]: "msg": "hello"

Serial Monitor Interaction

6.3 Verification Methods

OperationExpected Result
Power onConnect to Broker, start timed publishing
Use MQTT client (e.g., MQTTX) to publish to esp32/subSerial port prints received message

7. Common Problems

PhenomenonCauseSolution
connect() returns status 2Client ID occupiedUse unique ID, such as ESP32_<MAC address>
Not receiving messagesclient.loop() not called frequently enoughEnsure no long delay() in loop()
Compilation error, cannot find PubSubClient.hLibrary not installedInstall PubSubClient in library manager
Cannot receive messages from MQTTXPublish topic and subscription topic may not match the codeVerify publish and subscription topics match
HTTP Server Experiment
WIFI OTA Upgrade

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文