MQTT robot telemetry with ESP32: topics, QoS and code

Design MQTT topics for a robot, pick the right QoS, publish telemetry from an ESP32 and avoid the buffering and Wi-Fi traps that break it.

Reference
RE-871
Published
Updated
Read
7 min

About the author · Sources, testing and AI policy

Robot telemetry dashboard showing battery and speed charts

MQTT is the cheapest way to get robot telemetry onto a dashboard. One broker, a few topics and an ESP32 publishing at 0.5 Hz costs about 60 bytes per cycle, roughly 2.6 MB a day. This guide covers the topic design, what QoS the ESP32 library can actually publish, a working publisher with a non-blocking reconnect, the broker, and the faults that stop messages in the field. Protocol details are in the MQTT specification, listed under sources.

Why MQTT suits a robot

  • Messages are small and the link can be slow.
  • Publish and subscribe lets many dashboards read one robot.
  • The broker decouples the robot from whoever is watching it.
  • A Last Will message tells you when a robot drops off.
  • Retained messages show a new subscriber the last known state at once.
  • It runs on a 3.3 V ESP32 with a few KB of RAM per connection.

Design the topic tree first

robots/<robot_id>/status
robots/<robot_id>/battery
robots/<robot_id>/velocity
robots/<robot_id>/fault
robots/<robot_id>/cmd/velocity
robots/<robot_id>/cmd/estop
TopicDirectionQoS you wantRetained
statusRobot to broker1Yes
batteryRobot to broker0Yes
velocityRobot to broker0No
faultRobot to broker1Yes
cmd/velocityOperator to robot1No
cmd/estopOperator to robot1No

Keep commands and telemetry in separate subtrees. Access control then stays simple: the dashboard reads everything under the robot and writes only under cmd/.

QoS, and what PubSubClient can do

QoSGuaranteeUse for
0At most once, fire and forgetFast telemetry, velocity, battery
1At least once, may duplicateCommands, faults, status
2Exactly onceBilling or records, rarely a robot

One limit matters on the ESP32: the PubSubClient library publishes at QoS 0 only. It can subscribe at QoS 0 or 1 and set a QoS 1 Last Will, but a call to publish() always goes out at QoS 0. If a fault message must be acknowledged, use a different client library, or send it repeatedly until a command or status topic confirms it. The QoS 1 column above is what the design needs, not what PubSubClient sends.

QoS 1 can deliver duplicates, so make the receiving handler idempotent. A command with a sequence number that ignores repeats is safer than one that runs twice.

Worked example: how much data is this?

Take a velocity reading and a battery percentage, published to separate topics every 2 seconds. A QoS 0 PUBLISH packet is a 1-byte header, a 1-byte remaining length, a 2-byte topic length, the topic, and the payload.

MessageTopic lengthPayloadPacket size
robots/robot-01/velocity, payload 0.424 bytes3 bytes1 + 1 + 2 + 24 + 3 = 31 bytes
robots/robot-01/battery, payload 8723 bytes2 bytes1 + 1 + 2 + 23 + 2 = 29 bytes

One cycle is 31 + 29 = 60 bytes. At 0.5 Hz (every 2 seconds) that is 43,200 cycles a day, so 43,200 × 60 = 2.59 MB a day at the MQTT level. TCP, IP and Wi-Fi headers add more on the wire, so treat this as a floor, not a data-plan figure.

Now raise only velocity to 20 Hz: 31 bytes × 20 = 620 bytes per second, or 53.6 MB a day. That is about 21 times the whole slow cycle, from one topic. The rule: if a signal changes faster than a person can read it, publish it slower, or log it on the robot and send a summary.

A working ESP32 publisher

Connect, publish on a timer, and set a Last Will so the broker marks the robot offline when the link dies. The reconnect below is non-blocking, because a while loop with delay() stops the robot’s control code every time Wi-Fi drops.

#include <WiFi.h>
#include <PubSubClient.h>

WiFiClient net;
PubSubClient mqtt(net);

void reconnect() {
  static unsigned long lastTry = 0;
  if (millis() - lastTry < 2000) return;   // try every 2 s, never block
  lastTry = millis();
  if (WiFi.status() != WL_CONNECTED) return;
  if (mqtt.connect("robot-01", nullptr, nullptr,
      "robots/robot-01/status", 1, true, "offline")) {
    mqtt.publish("robots/robot-01/status", "online", true);
  }
}

void setup() {
  WiFi.begin("SSID", "PASSWORD");
  mqtt.setServer("192.168.1.50", 1883);
  mqtt.setBufferSize(512);
}

void loop() {
  if (!mqtt.connected()) reconnect();
  else mqtt.loop();

  static unsigned long last = 0;
  if (mqtt.connected() && millis() - last >= 2000) {
    last = millis();
    mqtt.publish("robots/robot-01/velocity", "0.4");
    mqtt.publish("robots/robot-01/battery", "87", true);
  }
}

Set the buffer size explicitly. The default packet limit is 256 bytes, and a larger JSON payload then fails without a warning. If publish() returns false, check size first.

The broker

Mosquitto on a small VPS or a Raspberry Pi handles a workshop full of robots. Open port 1883 only inside your network, and use 8883 with TLS if anything crosses the internet.

sudo apt install mosquitto mosquitto-clients
mosquitto_sub -h localhost -t 'robots/#' -v

Create a username and password per robot, and give the dashboard a separate read-only account. An open broker on a factory network is a remote-control hole.

From broker to dashboard

  • Node-RED is the fastest path to charts and alerts, and runs on the same Pi.
  • InfluxDB with Grafana is better for history and long-term trends.
  • Home Assistant suits small service robots and lab setups.
  • A Python subscriber writing to Postgres fits custom logic.

A simple subscriber that stores every message with a timestamp is often all a first deployment needs. Build the dashboard after the data is reliable.

If you see this, do this

SymptomLikely causeDo this
Messages stop after a few minutesKeepalive too short for Wi-Fi latencyRaise the keepalive with setKeepAlive() and test on your own Wi-Fi
publish() returns falsePayload larger than the bufferCall setBufferSize() above the packet size
Reconnect loopDuplicate client ID from a cloned deviceGive each robot its own ID
Dashboard shows stale dataRetained message never updated, or no Last WillSet the Last Will and republish on connect
Commands arrive twiceQoS 1 duplicateAdd a sequence number and ignore repeats
Robot slow or jerkyBlocking reconnect or publishing too oftenUse the non-blocking reconnect and publish slower

What not to put on MQTT

  • Safety stop commands over Wi-Fi. Hardwire the E-stop.
  • High-rate control loops. Use a local bus or micro-ROS.
  • Large images or point clouds. Send a link or a summary.
  • Credentials in plain text on port 1883 across the internet.
  • Anything you cannot afford to lose without an acknowledgement path.

Related: ESP32 pinout for robotics, micro-ROS tutorial, Raspberry Pi 5 robot guide, robot battery guide, mobile robot charging and docking.

Frequently asked questions

Is MQTT good for robot telemetry?

Yes for low-rate telemetry such as battery, status, faults and position. It is not suitable for safety stops or high-rate control loops, which should stay on hardware or a local bus.

Which QoS should I use for robot data?

QoS 0 for fast telemetry like velocity and battery, QoS 1 for commands and faults. QoS 2 is rarely worth the overhead on a robot. Remember that PubSubClient publishes at QoS 0 only.

Why does my ESP32 stop publishing to MQTT?

The usual causes are a payload bigger than the 256-byte default buffer, a keepalive too short for Wi-Fi latency, or a duplicate client ID after cloning a device.

Can I send emergency stop over MQTT?

No. A safety stop must be hardwired and independent of Wi-Fi, the broker and the network. MQTT can tell people that a stop happened, not perform it.

Do I need TLS for MQTT on a robot?

If traffic crosses the internet, yes: use port 8883 with certificates. Inside an isolated workshop network, port 1883 with per-device credentials is common but still needs access control.

Sources and further reading

  • MQTT.org: protocol specification and overview.
  • Eclipse Mosquitto: broker documentation and configuration.
  • PubSubClient: Arduino client library reference, including its QoS limits and buffer size.
  • Node-RED: dashboards and flows for MQTT data.

Last reviewed: November 2026. The byte counts above are MQTT-level arithmetic for the example topics, not network measurements. Test the code on your own board and broker before relying on it.

Pass it onWhatsAppLinkedIn

Keep reading

Continue learning

Free: the final-year project pack

A shortlist with BOMs, a report outline that matches the usual chapter scheme, a costing sheet and 40 viva questions. Built for the February–April submission season.

The Build Note

One short email when something is worth your bench time.

A new build sheet, a part price that moved, or a mistake worth avoiding. No daily drip, no recycled news.

One short email when a build or a price is worth your time. Unsubscribe in one click.