MQTT Basics: Publish and Subscribe

ReviewedBeginnerFreeAbout 6 min
NRF24
In short

MQTT Basics: Publish and Subscribe: the short answer

MQTT is a lightweight messaging protocol built for small devices. Instead of devices talking to each other directly, every device connects to a central server called a broker. Example: A clear, consistent topic tree makes wildcards work and lets you add rooms later without changing the dashboard.

Level
Beginner
Time
About 6 min
Topic
Communication
You will learn to

Send sensor readings from an ESP32 to an MQTT broker and control an LED from your phone using topics.

Before this: Connecting an ESP32 to Wi-Fi

MQTT is a lightweight messaging protocol built for small devices. Instead of devices talking to each other directly, every device connects to a central server called a broker. A device publishes a message to a topic, which is just a text path such as home/garden/soil. Any device or app subscribed to that topic receives the message. The sensor does not need to know who is listening, and the phone does not need to know the sensor's IP address.

Topics are organised like folders. Wildcards help when subscribing: + matches one level (home/+/soil gets soil readings from every room) and # matches everything below (home/garden/#). Keep payloads small and simple: a number like 42, or a short JSON object like {"soil":42,"bat":3.9}. Use separate topics for readings and commands, for example home/garden/pump/set for commands and home/garden/pump/state for the reported state.

To start, run the free Mosquitto broker on a laptop or Raspberry Pi, or use a public test broker for experiments only (anyone can read public brokers). On the ESP32, the PubSubClient library connects with client.connect("garden-01"), publishes with client.publish("home/garden/soil", "42") and subscribes with client.subscribe("home/garden/pump/set") plus a callback function. Call client.loop() often, and reconnect when the connection drops. A phone app such as an MQTT dashboard app then shows readings and sends commands.

Why publish and subscribe

With plain HTTP, a device calls a server and waits for an answer. With MQTT, every device keeps one small connection open to a broker and exchanges short messages. Senders and receivers never meet: the sensor publishes to a topic and anything subscribed gets it. You can add a dashboard, a logger or a second phone without changing the sensor code.

That fits small devices: an MQTT message can be only a few bytes, and a connection can stay open for days, while a device sleeps and wakes.

Quality of service, retain and last will

QoS 0 sends once, with no confirmation, and is fine for readings you send every few seconds. QoS 1 resends until the broker confirms, so a message arrives at least once; use it for commands. QoS 2 guarantees exactly once but costs more and is rarely needed.

A retained message is stored by the broker and given to new subscribers straight away. It is the right setting for state topics such as home/garden/pump/state, so a freshly opened dashboard shows the current state immediately. A last-will message is one the broker sends for you if the device vanishes without saying goodbye, so a dashboard can show "offline".

Designing topics

Use a structure that goes from general to specific, such as home/garden/soil/moisture, and keep names lowercase without spaces. Put a device name or id at a stable place, so a wildcard such as home/+/battery collects a value from every room. Use separate topics for state and commands (…/state and …/set), so a device does not receive its own reports as commands.

Do not put secrets in topics, and do not start a topic with a slash, which creates an empty first level.

Security and reliability

Public test brokers are readable by anyone and are only for experiments. For real use, run your own broker with a username and password, and use TLS (port 8883) if the data travels over the internet. Give each device its own credentials so you can disable a lost one.

Reconnect when the link drops, and do it with a delay that grows, so a broker restart is not flooded by every device at once. Call client.loop() often; a long delay() in the main loop starves the connection and the broker drops the client.

Common mistakes
  • Using the same client ID on two devices. The broker disconnects the older one, and they take turns kicking each other off.
  • Blocking the loop with delay() so the keep-alive ping is missed.
  • Publishing commands and states on the same topic, causing a feedback loop.
Worked example

Design topics for a two-room sensor system

  1. Each room has temperature and humidity: home/bedroom/temp, home/bedroom/hum, home/hall/temp, home/hall/hum.
  2. A fan in the bedroom takes commands on home/bedroom/fan/set and reports home/bedroom/fan/state.
  3. A dashboard subscribes to home/+/temp to show both rooms' temperatures.
  4. A logger subscribes to home/# to record everything.

Result. A clear, consistent topic tree makes wildcards work and lets you add rooms later without changing the dashboard.

Try it

Install Mosquitto on a laptop or Raspberry Pi. Make an ESP32 publish a potentiometer reading every 5 seconds to lab/pot, and subscribe to lab/led/set so that sending ON or OFF from mosquitto_pub or a phone app switches an LED.

Check yourself

3 quick questions

  1. What does an MQTT broker do?

  2. Which subscription receives home/kitchen/temp and home/hall/temp?

  3. Why are public test brokers only for experiments?

Common questions

What will I learn in "MQTT Basics: Publish and Subscribe"?

Send sensor readings from an ESP32 to an MQTT broker and control an LED from your phone using topics.

How do I design topics for a two-room sensor system?

Each room has temperature and humidity: home/bedroom/temp, home/bedroom/hum, home/hall/temp, home/hall/hum. A fan in the bedroom takes commands on home/bedroom/fan/set and reports home/bedroom/fan/state. A dashboard subscribes to home/+/temp to show both rooms' temperatures. A logger subscribes to home/# to record everything. A clear, consistent topic tree makes wildcards work and lets you add rooms later without changing the dashboard.

What does an MQTT broker do?

Receives published messages and forwards them to subscribers. The broker sits between publishers and subscribers.

Which subscription receives home/kitchen/temp and home/hall/temp?

home/+/temp. + matches exactly one topic level.

Why are public test brokers only for experiments?

Anyone can read or publish to your topics. Use your own broker with a password for real projects.