STM32 MQTT Tutorial: Publish, Subscribe Over WiFi (Examples)

In this tutorial, we’ll discuss how to use STM32 MQTT over WiFi to publish and subscribe to an MQTT broker, using an ESP32-C3 as a WiFi co-processor. You’ll learn how MQTT works (broker, topics, QoS, retained messages, and the last will), how the ESP32-C3’s built-in MQTT client (ESP-AT) connects an STM32 to a broker, and how to publish sensor readings and receive commands on the STM32.

Then, we’ll build three STM32 MQTT example projects with our ESP_AT driver: publishing the STM32’s internal temperature every 5 seconds, controlling the Blue Pill’s LED from any MQTT client with a retained state and an online/offline status, and the same over TLS (MQTT on port 8883). We’ll also measure the connect time, the publish time, and the round trip from a PC to the LED and back. This is the sixth part of our STM32 WiFi tutorial series. Without further ado, let’s get right into it!

Note: The STM32 code examples in this tutorial are tested with: STM32 Blue Pill (STM32F103C8T6), ESP32-C3 Core Board with ESP-AT firmware, and the test.mosquitto.org broker.


What Is MQTT? Publish and Subscribe Explained

MQTT is a small messaging protocol for IoT devices. Devices don’t talk to each other directly; they all keep one TCP connection to a server called the broker. A device publishes a message to a topic (a name like home/kitchen/temperature), and the broker forwards it to every client that subscribed to that topic. The publisher doesn’t need to know who listens, and a phone, a PC, and other boards can all read the same readings or send the same commands.

MQTT TermWhat It Means
BrokerThe server every client connects to (Mosquitto, HiveMQ, EMQX). It receives published messages and forwards them to the subscribers
TopicA message’s address, with levels split by /. A subscription can use + (one level) or # (all levels below)
Publish / SubscribeSend a message to a topic / ask the broker for every message on a topic
QoS 0, 1, 2Delivery guarantee: 0 = at most once (no acknowledgment), 1 = at least once (acknowledged, may repeat), 2 = exactly once
Retained messageThe broker keeps the last retained message of a topic and sends it to every new subscriber at once (good for a state, like the LED is ON)
Last willA message the broker publishes for a client that vanishes without disconnecting (power off, WiFi lost), like offline
KeepaliveThe longest time between two packets from the client. If the broker hears nothing for 1.5 times this, it drops the client and publishes its last will
STM32 MQTT publish and subscribe: the STM32 and ESP32-C3 publish the temperature and LED state to the broker, which forwards them to a PC and a phone, and the PC publishes LED commands back to the STM32


STM32 MQTT Over WiFi: How It Works

The STM32 doesn’t need an MQTT library or a TCP/IP stack. The ESP32-C3’s ESP-AT firmware has an MQTT client built in: it connects to the broker, keeps the connection alive, and even reconnects by itself. The STM32 sends it AT commands over the UART and receives the subscribed messages as +MQTTSUBRECV lines:

StepAT Command or MessageWhat It Does
Client settingsAT+MQTTUSERCFG=0,1,"<client id>","<user>","<password>",0,0,""Scheme 1 = MQTT over TCP, 2 = MQTT over TLS
Connection settings (optional)AT+MQTTCONNCFG=0,<keepalive>,0,"<will topic>","<will message>",<qos>,<retain>Keepalive, clean session, last will
ConnectAT+MQTTCONN=0,"test.mosquitto.org",1883,1The last 1 = reconnect automatically. Replies +MQTTCONNECTED:... and OK
Publish textAT+MQTTPUB=0,"<topic>","<data>",<qos>,<retain>For short text messages
Publish raw dataAT+MQTTPUBRAW=0,"<topic>",<length>,<qos>,<retain>Long or binary data, sent after the > prompt; ends with +MQTTPUB:OK
SubscribeAT+MQTTSUB=0,"<topic>",<qos>Messages then arrive as +MQTTSUBRECV:0,"<topic>",<length>,<data>
Unsubscribe / closeAT+MQTTUNSUB=0,"<topic>", AT+MQTTCLEAN=0Stop a subscription / close the connection
Connection state+MQTTCONNECTED, +MQTTDISCONNECTEDSent by the module at any time, also after its own reconnect

The full list is in Espressif’s ESP-AT MQTT AT commands reference. Commas, quotes, and backslashes inside a topic or message must be escaped with a backslash; our driver does that for you.

Note: The ESP-01 (ESP8266) with the NonOS AT 1.7.6 firmware from the ESP8266 AT commands tutorial has no MQTT commands. For this tutorial, use an ESP32-C3 (or another ESP32) with ESP-AT, as in the ESP32 AT commands tutorial.

STM32 MQTT over WiFi architecture: the ESP32-C3 runs the WiFi, TCP/IP and the MQTT client with ESP-AT, and the STM32 sends AT commands over the UART


STM32 MQTT Wiring and CubeMX Configuration

Required Parts

QTY.Component NameAmazon.comAliExpress
1STM32 Blue Pill (STM32F103C8T6)AmazonAliExpress
1ST-Link V2 DebuggerAmazonAliExpress
1ESP32-C3 board (ESP32-C3 SuperMini; we use the WeAct ESP32-C3 Core Board)AmazonAliExpress
1USB-TTL (UART) Converter, 3.3VAmazonAliExpress
1BreadBoardAmazonAliExpress
1Jumper Wires PackAmazonAliExpress

STM32 ESP32-C3 Wiring

The wiring is the same as in the previous parts of this series: the STM32’s USART1 goes to the ESP32-C3’s AT port, and USART2’s TX pin goes to a USB-TTL converter for the log.

PA9 USART1 TX, goes to the ESP32-C3 GPIO6 (AT RX).

PA10 USART1 RX, goes to the ESP32-C3 GPIO7 (AT TX).

PA2 USART2 TX, goes to the USB-TTL converter’s RX: the log to your PC at 115200 baud.

GND Goes to the ESP32-C3 GND and the USB-TTL GND: common ground.

STM32 MQTT wiring: Blue Pill PA9 to ESP32-C3 GPIO6, PA10 to GPIO7, and PA2 to a USB-TTL converter

STM32 Blue Pill ESP32-C3 / USB-TTL PA9 (USART1 TX) GPIO6 (AT RX) PA10 (USART1 RX) GPIO7 (AT TX) GND GND PA2 (USART2 TX) USB-TTL RX GND USB-TTL GND

This is my test setup for this tutorial: the STM32 Blue Pill and the ESP32-C3 on a breadboard:

STM32 Blue Pill wired to a WeAct ESP32-C3 Core Board on a breadboard for the STM32 MQTT examples

STM32 CubeMX Configuration

Start from the CubeMX configuration of the ESP32 AT commands tutorial (every step has a screenshot there): USART1 at 115200 baud with RX DMA in Circular mode and the USART1 global interrupt for the ESP32-C3, USART2 for the log, PC13 as the LED output, and the 72MHz clock.

STM32CubeMX USART1 DMA Settings: USART1_RX in Circular mode and USART1_TX in Normal mode for the ESP_AT driver

The examples publish the chip temperature, so also enable ADC1 with the Temperature Sensor Channel, set the sampling time to 239.5 cycles, and set the ADC clock to 12MHz (PCLK2 / 6), as in the STM32 web server tutorial. The STM32 internal temperature sensor tutorial explains these settings.


STM32 MQTT Functions (ESP_AT Driver)

We added an MQTT client to our ESP_AT driver for this tutorial. Every function starts a job and returns at once (the result arrives as ESP_AT_EVT_JOB_DONE), and each one has a _Blocking twin that waits for the result:

Function or EventWhat It Does
ESP_AT_MqttConnect(&esp, &mqtt)Connects to the broker set in an ESP_AT_MqttConfigType (host, port, TLS, client ID, user, password, keepalive, last will, auto reconnect)
ESP_AT_MqttPublishString(&esp, topic, text, qos, retain)Publishes a text message
ESP_AT_MqttPublish(&esp, topic, data, len, qos, retain)Publishes any data. Short text goes in one AT+MQTTPUB; long or binary data goes through AT+MQTTPUBRAW
ESP_AT_MqttSubscribe(&esp, topic, qos) / ESP_AT_MqttUnsubscribe(&esp, topic)Starts or stops a subscription
ESP_AT_MqttDisconnect(&esp)Closes the connection (AT+MQTTCLEAN=0)
ESP_AT_EVT_MQTT_DATAA message arrived: d->topic, d->data, d->len
ESP_AT_EVT_MQTT_CONNECTED / _DISCONNECTED, esp.mqttConnectedThe broker connection came up or was lost

Choosing an MQTT Broker for Testing

The examples use test.mosquitto.org, a free public test broker, so they work without installing anything. Keep in mind that anyone can read and write every topic on a public broker, so never send passwords or private data there, and use a topic name nobody else uses. Our examples add the STM32’s unique chip ID to every topic ( deepbluembedded/stm32/bluepill-0668ff55/...).

BrokerPortGood For
test.mosquitto.org1883 (TCP), 8883 (TLS)Quick tests, no account. Public: no private data
Mosquitto on your PC or a Raspberry Pi1883Your own network, private, fast
HiveMQ Cloud, EMQX Cloud8883 (TLS)Free cloud tiers with a user name and password, reachable from anywhere

To watch the messages on your PC, use a desktop MQTT client like MQTT Explorer or MQTTX, or the Mosquitto command line tools:


STM32 MQTT Example 1: Publish Sensor Data

In the first example project, the STM32 connects to test.mosquitto.org and publishes its internal temperature as a small JSON message every 5 seconds:

Wiring: PA9 to ESP32-C3 GPIO6, PA10 to GPIO7, PA2 to the USB-TTL RX, and GND to both.

Write your WiFi name and password in Core/Inc/wifi_secrets.h:

Here is The Application Code For This Example Project (main.c). Only the USER CODE sections are shown; the rest of the file is generated by CubeMX:

STM32 MQTT Publish Example Code Explanation

The client ID and the topic are built from the STM32’s unique ID ( HAL_GetUIDw0()), so two boards running the same code never share a client ID. A broker drops the older connection when a second client connects with the same ID.

ESP_AT_MqttConfigType holds the broker settings: the host, the port, .tls = 0 for plain MQTT, a 60-second keepalive, and .autoReconnect = 1, which tells the ESP32-C3 to reconnect to the broker by itself after a WiFi or broker drop. ESP_AT_MqttConnect_Blocking() sends the AT commands and waits for +MQTTCONNECTED.

In the main loop, every PUBLISH_MS (5 seconds), the code reads the temperature sensor, formats the JSON message with snprintf(), and starts the publish with ESP_AT_MqttPublishString() (QoS 0, not retained). It only publishes while esp.mqttConnected is set, and the result arrives in OnEvent() as ESP_AT_EVT_JOB_DONE, where the code logs it with the time it took.

ReadTemperature() averages 16 conversions of the internal temperature sensor and converts them to °C with the datasheet’s V25 and Avg_Slope values, as explained in the STM32 internal temperature sensor tutorial.

STM32 MQTT Publish Example Testing

This is the STM32’s log after a reset. The “connection lost” line comes from the connection of the previous run: the ESP32-C3 still held it when the STM32 restarted, and our driver closes it before connecting again.

STM32 MQTT publish example serial log: broker connect time and every publish with its time
STM32 MQTT publish example serial log: broker connect time and every publish with its time

And this is a subscriber on my PC ( deepbluembedded/stm32/+/temperature), receiving a message every 5 seconds:


STM32 MQTT Example 2: Subscribe to Control an LED

In this example project, the STM32 subscribes to a command topic and switches its LED (PC13) when a message arrives, and it reports its LED state and its online/offline status. These are the topics it uses:

Topic (after deepbluembedded/stm32/<id>/)DirectionMessages
led/setTo the STM32 (subscribed, QoS 1)ON, OFF, TOGGLE
led/stateFrom the STM32 (QoS 1, retained)ON or OFF, after every change and every (re)connect
statusFrom the STM32 and the broker (QoS 1, retained)online after connecting; offline is the last will
temperatureFrom the STM32 (QoS 0)The chip temperature every 10 seconds

Because led/state and status are retained, an app that subscribes later gets the current LED state and whether the board is online at once, without waiting for the next change.

Here is The Application Code For This Example Project (main.c). Only the USER CODE sections are shown; the rest of the file is generated by CubeMX:

STM32 MQTT Subscribe Example Code Explanation

The last will is set in the connection settings: .willTopic = tStatus, .willMessage = "offline", .willQos = 1, .willRetain = 1. The broker stores it at connect time and publishes it if the board disappears. The keepalive is 30 seconds, so the broker notices a silent board within 45 seconds.

When the broker connection comes up (also after the ESP32-C3 reconnects by itself), OnEvent() gets ESP_AT_EVT_MQTT_CONNECTED and sets setupPending. The main loop then runs three steps, one job at a time: publish online (retained), subscribe to led/set, and publish the LED state. Subscribing again after every reconnect makes sure the subscription is never lost.

A message on a subscribed topic arrives as ESP_AT_EVT_MQTT_DATA. The code compares the topic with tSet and passes the message to LedCommand(), which switches the LED and sets statePending. The main loop then publishes the new state. Nothing is published from inside the event callback, because the driver runs one job at a time.

Tip: Set SHOW_AT_TRAFFIC to 1 to log every AT command and reply on USART2. It’s the quickest way to see what the module does when something doesn’t work.

STM32 MQTT Subscribe Example Testing

This is the real hardware testing result for this example project. On the left is a small MQTT client page in my browser ( mqtt-led-client.html in the download folder; it talks to test.mosquitto.org over WebSocket), and on the right is my webcam on the Blue Pill. Every click publishes ON or OFF to led/set, the PC13 LED switches a moment later, and the page shows the led/state message the STM32 sends back.

STM32 MQTT demo: publishing ON and OFF to the led/set topic from a browser MQTT client switches the Blue Pill’s PC13 LED through the test.mosquitto.org broker

I sent ON and OFF to led/set from my PC, waiting each time for led/state to come back through the broker. The STM32 starts publishing the new state 3 ms after the command arrives:

STM32 MQTT subscribe example serial log: led/set commands and the led/state replies
STM32 MQTT subscribe example serial log: led/set commands and the led/state replies

The PC side measured the full round trip (PC to the broker, to the ESP32-C3 and the STM32, the LED switch, and the state back through the broker to the PC). The median was 156ms, and the broker’s ping time from my PC was 62ms:

To test the last will, I made the ESP32-C3 drop its WiFi connection (a new join, as after a reset). About 5 seconds later, the broker published offline on the status topic, and a moment after the board reconnected, online replaced it.


STM32 MQTT Example 3: MQTT Over TLS (Port 8883)

MQTT on port 1883 is plain text: anyone on the path can read the messages and the password. With TLS, the ESP32-C3 encrypts the connection, and the STM32 code stays the same. In Example 2, set:

This sets .tls = 1 (scheme 2 in AT+MQTTUSERCFG) and port 8883. All the TLS work runs on the ESP32-C3, so the STM32 needs no extra RAM or flash. This is the result:

STM32 MQTT over TLS serial log: connecting to test.mosquitto.org on port 8883
STM32 MQTT over TLS serial log: connecting to test.mosquitto.org on port 8883

The TLS handshake made AT+MQTTCONN take about 1.05 seconds instead of 0.18 seconds, but once connected, the round trip was almost the same (162ms vs 156ms). The connection is encrypted, but scheme 2 does not check the broker’s certificate. To check it, ESP-AT needs the broker’s CA certificate flashed into its certificate partition (scheme 4), which is beyond this tutorial.


STM32 MQTT Measured: Connect, Publish and Round Trip Times

All measured with test.mosquitto.org (62ms ping from my PC) and the UART at 115200 baud:

MeasurementMQTT (port 1883)MQTT over TLS (port 8883)
AT+MQTTCONN (connect to the broker)173 to 237ms1030 to 1149ms
Full connect after an STM32 reset (close the old connection, rejoin, connect)3.3 to 4.1s4.9 to 5.1s
Publish a 40-byte message (AT+MQTTPUB until OK)18ms–
Command to LED state round trip through the broker (median of 10)156ms162ms
From the command arriving to the state publish starting2 to 3ms2 to 3ms

The slowest part is the reconnect after an STM32 reset: the ESP32-C3 keeps its old broker connection while the STM32 restarts, and closing it with AT+MQTTCLEAN takes a few seconds. Our driver waits up to 10 seconds for it. If your STM32 resets often, you can skip the WiFi join and the reconnect when AT+MQTTCONN? shows the module is still connected.


STM32 MQTT Troubleshooting

AT+MQTTUSERCFG or AT+MQTTCONN returns ERROR

Check that the firmware has MQTT (ESP-AT on an ESP32; NonOS AT 1.7.6 on the ESP-01 has none) and that the WiFi is connected. An ERROR right after an STM32 reset usually means the module was still closing the old connection (“busy p…”); give AT+MQTTCLEAN a few seconds, as our driver does.

Connected, but no messages arrive

The subscribe topic must match the publish topic exactly (topics are case-sensitive), and both clients must use the same broker. Subscribe to deepbluembedded/stm32/# in MQTT Explorer to see every message under the prefix.

The connection drops every few minutes

Two clients with the same client ID kick each other off the broker. Make the client ID unique (our examples add the chip’s unique ID). Also check the keepalive: the ESP32-C3 sends the pings by itself, so the STM32 code doesn’t need to.

Messages with commas or quotes are cut

Inside AT+MQTTPUB, commas, quotes, and backslashes must be escaped with a backslash. ESP_AT_MqttPublish() escapes them, and it switches to AT+MQTTPUBRAW for binary or long messages.


STM32 MQTT FAQ

Does the STM32 need an MQTT library like Paho or the LwIP MQTT client?

Not with an ESP32-C3 running ESP-AT. The MQTT client, TCP/IP, and TLS run on the ESP32-C3, and the STM32 only sends AT commands. You need an MQTT library (Paho Embedded, LwIP MQTT, or Mongoose) for an STM32 with Ethernet, a W5500, or a cellular modem without MQTT commands.

Can the STM32 be the MQTT broker?

No. A broker runs on a PC, a Raspberry Pi, a server, or a cloud service. The STM32 is a client that connects to it.

Which QoS should I use?

QoS 0 for frequent readings (losing one doesn’t matter), QoS 1 for commands and states (the broker acknowledges them). QoS 2 is rarely needed on a microcontroller.

How much RAM and flash does the MQTT code use on the STM32?

The whole Example 2 project (driver, MQTT, ADC, and HAL) builds to about 25KB of flash and 6.6KB of RAM in a Release build, and the driver’s handle is about 4KB of that RAM. TLS adds nothing on the STM32 side.


STM32 WiFi Tutorial Series

This tutorial is the sixth part of our STM32 WiFi tutorial series:

PartTutorialWhat You’ll Build
1STM32 WiFiChoosing a WiFi module, quick start, ESP32-C3 vs ESP8266 measured
2ESP8266 AT Commands With STM32ESP8266 AT firmware, commands, and our ESP_AT driver
3ESP32 AT Commands With STM32ESP-AT firmware, commands, SNTP time, and our ESP_AT driver
4STM32 HTTP Client Over WiFiGET, POST, HTTPS, and JSON parsing
5STM32 Web Server Over WiFiControl GPIO from a browser, live temperature dashboard
6STM32 MQTT Tutorial (this tutorial)Publish and subscribe, last will, MQTT over TLS
7STM32 OTA Firmware Update Over WiFiBootloader, dual-slot update, CRC32 check
8STM32 WebSocket With ESP32WebSocket server on the STM32, live dashboard

Download STM32 MQTT Example Projects (Publish, Subscribe, TLS)

Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.

Wrap Up

To conclude this tutorial, we’ve connected an STM32 to an MQTT broker over WiFi with an ESP32-C3 and our ESP_AT driver. The ESP32-C3’s built-in MQTT client handles the broker connection, the keepalive, TLS, and reconnects, while the STM32 publishes its readings and reacts to commands with a few function calls. We published the chip temperature, controlled the LED with a retained state and a last will, switched to TLS, and measured a 156ms round trip from a PC to the LED and back.

In the next part of this series, we’ll update the STM32’s firmware over WiFi (OTA).

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment