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

MQTT Communication Experiment


MQTT Communication Experiment1. MQTT Overview2. Core Concepts2.1 Publish/Subscribe Model2.2 Configuration Parameters2.3 Core API2.4 Topics and Messages3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Explained5.1 Creating the MQTT Client5.2 Message Callback5.3 Main Loop6. Operating Procedures6.1 Flashing and Running6.2 Serial Output Example6.3 Verification Methods7. Common Problems


1. MQTT Overview

MQTT (Message Queuing Telemetry Transport) is the most mainstream lightweight publish/subscribe messaging protocol in the IoT field. It is based on TCP and uses the publish/subscribe (Pub/Sub) mode instead of the traditional client-server direct connection mode, achieving temporal and spatial decoupling between producers and consumers.

In this experiment the ESP32-S3 connects to the public Broker broker.emqx.io, publishes messages to the test/esp32/send topic, and subscribes to the test/esp32/recv topic.

Typical application scenarios:

Application TypeExample
Sensor reportingTemperature/humidity published to the cloud periodically
Remote controlPhone App publishes control commands, ESP32 subscribes and receives
Multi-device linkageDoor magnet sensor triggers -> alarm responds
Smart homeManage devices through platforms such as Home Assistant / EMQX

This experiment depends on the umqtt.simple library (built into MicroPython or uploaded separately). Using a public Broker requires no self-built server.


2. Core Concepts

2.1 Publish/Subscribe Model

​x
​
┌──────────┐ publish("test/topic", msg)   ┌──────────┐  
│ ESP32-S3 │ ───────────────────────────→ │  Broker  │
│          │ ←─────────────────────────── │ (EMQX)   │
│          │  subscribe("test/topic")     └────┬─────┘
└──────────┘                                   │
                                    pushed to all subscribers on publish
                                          ┌────┴───────┐
                                          │ Phone APP  │
                                          └────────────┘
  • Broker: the message relay station, responsible for receiving publishes and pushing to subscribers
  • Topic: the message topic, e.g. home/livingroom/temperature
  • Publish: publish a message to a specified topic
  • Subscribe: subscribe to a topic; the Broker pushes messages on that topic to you

2.2 Configuration Parameters

ParameterDescriptionValue Used in This Experiment
BROKERMQTT broker addressbroker.emqx.io (public)
TOPIC_PUBPublish topictest/esp32/send
TOPIC_SUBSubscribe topictest/esp32/recv
CLIENT_IDClient identifier (must be unique)esp32s3_mqtt

2.3 Core API

xxxxxxxxxx
from umqtt.simple import MQTTClient
​
# create
client = MQTTClient("client_id", "broker.emqx.io", port=1883)
client.set_callback(on_message)          # set callback
client.connect()                         # connect Broker
client.subscribe("topic/sub")            # subscribe
client.publish("topic/pub", "hello")     # publish
client.check_msg()              # check for subscribed messages

2.4 Topics and Messages

This experiment defines two topics; the ESP32 uses them to interact with external clients (such as MQTTX):

TopicDirectionQoSMessage ContentPeriod
test/esp32/sendESP32 -> Broker0"Hello ESP32 MQTT"Every 3s
test/esp32/recvBroker -> ESP320Any text (sent by MQTTX)Determined by the other side

QoS 0 (At most once): the message is delivered at most once and delivery is not guaranteed. Suitable for lightweight periodic sensor reporting.

Message flow:

xxxxxxxxxx
ESP32-S3  --publish("test/esp32/send", "Hello ESP32 MQTT")-->  Broker  --forward-->  MQTTX (subscriber)
ESP32-S3  <--subscribe("test/esp32/recv")----------------  Broker  <--publish--  MQTTX (publisher)

The ESP32 publishes and subscribes to separate topics to avoid receiving its own messages. If you want a self-send/self-receive loopback test, set TOPIC_PUB and TOPIC_SUB to the same topic.


3. Hardware Dependencies

The ESP32-S3 has built-in WiFi and needs access to the public Broker (broker.emqx.io). No PC or self-built server is required.


4. Project Architecture and Flow

xxxxxxxxxx
Script execution (single-file .py)
  |
  |- wifi_init(): connect to WiFi (STA mode)
  |- create MQTTClient -> connect() -> subscribe()
  |
  `- while True:
       |- publish(TOPIC_PUB, "Hello ESP32 MQTT")   // publish
       |- check_msg()                               // check subscription
       `- sleep(3s)

5. Source Code Explained

Full source code: Source Code -> MicroPython -> 4.Network Protocols -> MQTT -> MQTT.py

5.1 Creating the MQTT Client

Use the umqtt.simple library to connect to the public Broker broker.emqx.io:1883, set the callback, and subscribe to the target topic.

xxxxxxxxxx
from umqtt.simple import MQTTClient
​
BROKER     = "broker.emqx.io"           # public broker
TOPIC_PUB  = "test/esp32/send"          # publish topic
TOPIC_SUB  = "test/esp32/recv"          # subscribe topic
CLIENT_ID  = "esp32s3_mqtt"             # unique client ID
​
client = MQTTClient(CLIENT_ID, BROKER, port=1883)
client.set_callback(on_message)         # callback on message
client.connect()
client.subscribe(TOPIC_SUB)

5.2 Message Callback

Automatically called when the Broker pushes a subscribed message; the parameters are topic and msg (both bytes).

xxxxxxxxxx
def on_message(topic, msg):
    """received subscribed message"""
    print(f"[Received] {topic.decode()} -> {msg.decode()}")

5.3 Main Loop

Publishes one message every 3s -> check_msg() checks whether any subscribed message has arrived.

xxxxxxxxxx
while True:
    msg = "Hello ESP32 MQTT"
    client.publish(TOPIC_PUB, msg)       # publish
    print(f"[Sent] {msg}")
​
    client.check_msg()                   # check for messages
    time.sleep(3)

6. Operating Procedures

6.1 Flashing and Running

Thonny IDE steps: See MicroPython -> 1. Before Development -> 3.Thonny IDE.

  1. Modify WIFI_SSID / WIFI_PASS

    用户设置

  2. Run MQTT.py

  3. (Optional) Install an MQTT debugging tool (such as MQTTX) on the PCMQTTX图例

    • Create a new connection with broker.emqx.io:1883 (the public Broker requires no username/password),
    • Subscribe to test/esp32/send to see the messages published by the ESP32,
    • Publish a message to test/esp32/recv and the ESP32 will receive it.

    MQTTx窗口预览

    MQTTx窗口打印

6.2 Serial Output Example

xxxxxxxxxx
========== MQTT CLIENT ==========
[WiFi] Connecting to 'Yahboom2' ...
[WiFi] Connected! IP: 192.168.11.229
[MQTT] Connected to broker.emqx.io
[MQTT] Subscribed: test/esp32/recv
[Sent] Hello ESP32 MQTT
[Sent] Hello ESP32 MQTT
[Recv] test/esp32/recv -> "msg": "hello"
​
[Recv] test/esp32/recv -> "msg": "hello"
​
[Recv] test/esp32/recv -> "msg": "hello"
​
[Sent] Hello ESP32 MQTT
[Sent] Hello ESP32 MQTT

窗口打印

6.3 Verification Methods

OperationExpected Result
Subscribe to test/esp32/send with MQTTXReceives "Hello ESP32 MQTT" every 3s
Use MQTTX to send hello to test/esp32/recvThe ESP32 serial prints [Received] test/esp32/recv -> hello

7. Common Problems

SymptomCauseSolution
ImportError: no module named 'umqtt'Firmware does not include the umqtt libraryUpload umqtt/simple.py to the ESP32 manually
Timeout connecting to BrokerNetwork unreachable or Broker unreachableping broker.emqx.io to test reachability
check_msg() has no callbackset_callback() or subscribe() not calledConfirm all three steps in section 5.1 are complete
Client ID conflictTwo devices use the same IDUse a unique ID, e.g. esp32s3_mqtt_<last 4 of MAC>
No auto-reconnect after Broker disconnectumqtt.simple has no built-in reconnect mechanismDetect OSError in try/except; after disconnect, call connect() + subscribe() again
HTTP Server Experiment
Bluetooth Fundamentals

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/中文