MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe network protocol designed for efficient communication in constrained environments. Originally developed by IBM in the late 1990s, MQTT has become a standard for IoT (Internet of Things) systems due to its low bandwidth requirements and minimal overhead. It is mostly used in Home Automation systems, Industrial IoT applications and Mobile Messaging and Telemetry.
There are advantages which mare MQTT the protocol of choice for deploying scalable applications, such as being lightweight and efficient – ideal for low-power and low-bandwidth environments, decouples producers and consumers of data and scales well for large networks of devices.
sensors/temperature/room1).sensors/+/room1) to match multiple topics.MQTT uses a topic-based publish-subscribe model, and part of its flexibility comes from the use of wildcard characters in topic subscriptions.
/):Example topics: * ''sensors/temperature/room1'' * ''sensors/humidity/room2''
sensors/+/room1Matches: * ''sensors/temperature/room1'' * ''sensors/humidity/room1''
Does **not** match: * ''sensors/room1'' * ''sensors/temperature/office/room1''
sensors/#Matches: * ''sensors/temperature'' * ''sensors/temperature/room1'' * ''sensors/humidity/room2/sensor3''
# alone matches all topics.# must appear only at the end of the topic filter.+ must occupy an entire level (between slashes).sensor/+/status subscribes to:sensor/device1/statussensor/device2/status+ to match variations at a single level.# to subscribe to entire branches of the topic tree.# in production if not necessary — it can overwhelm clients with messages.In this lab, you'll interact with an MQTT broker, publish sensor data from your Sparrow sensor node, and visualize real-time telemetry. Familiarity with topics and QoS settings will be essential to design robust IoT communication systems.
You will need to add this to your Platformio project:
; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32-c6-sparrow] platform = https://github.com/pioarduino/platform-espressif32/releases/download/54.03.20/platform-espressif32.zip board = esp32-c6-devkitm-1 framework = arduino build_flags = -D ARDUINO_USB_MODE=1 -D ARDUINO_USB_CDC_ON_BOOT=1 -D ESP32_C6_env monitor_speed = 115200 lib_deps = adafruit/Adafruit NeoPixel@^1.11.0 adafruit/Adafruit BME680 Library bblanchon/ArduinoJson @ ^7 256dpi/MQTT @ ^2.5.2 knolleary/PubSubClient @ ^2.8
This example connects an ESP32 to Wi-Fi and establishes an MQTT connection to a public broker (test.mosquitto.org). It sets up a unique client ID based on the ESP32’s MAC address, registers a “Last Will” message so that if the device disconnects unexpectedly, the broker automatically marks it as offline, and then publishes an “online” status when connected. It also subscribes to all topics under a user-defined base topic (like iot/studentname/#), so it can receive messages addressed to that namespace, and logs any received messages to the serial monitor.
Once connected, the ESP32 enters a loop where it continuously maintains the MQTT session, reconnects if needed, and publishes a heartbeat message every five seconds containing its uptime in milliseconds. This heartbeat acts as a regular signal that the device is alive. The code’s use of non-blocking MQTT functions keeps the system responsive, while the combination of retained status messages and the Last Will feature ensures other clients always know the ESP32’s current state — whether it’s online, offline, or actively sending updates.
Click here to get the code for this example.
After building and uploading to your Sparrow node, test it out using this link.
This example, once connected, subscribes to a topic that controls an RGB LED connected to the board. Whenever a new MQTT message arrives on that topic, the ESP32 reads the JSON payload, extracts the red, green, blue, and brightness values, and updates the LED accordingly.
After setting the LED color, the device publishes an acknowledgment message to a separate MQTT topic, confirming the values it received and applied. This acknowledgment lets any remote controller or dashboard know that the LED update was successful. The whole process uses the non-blocking, event-driven design of the 256dpi library, meaning it can handle MQTT communication efficiently without freezing the microcontroller’s main loop. In essence, this sketch turns the ESP32 into a small, networked RGB controller that listens for MQTT commands and reports its actions back to the broker.
Click here to get the code for this example.
Test it out using this link.
Every ten seconds, the ESP32 reads environmental data from the on-board BME680 sensor—including temperature, humidity, pressure, and gas resistance—and packages those readings into a JSON message. It then publishes this JSON payload to an MQTT topic dedicated to that device’s sensor data. Any other MQTT clients subscribed to that topic can instantly receive and process the latest environmental information, such as for logging, visualization, or automation. In short, this code makes the ESP32 function as a small, networked environmental node that continuously streams live sensor data to the MQTT ecosystem while maintaining reliable connection status reporting.
Click here to get the code for this example.
Test it out using this link.
This example turns the ESP32 into a fully interactive MQTT client that both publishes and subscribes to topics on a broker using QoS and retain messages. When the device connects, it registers itself with a unique client ID and announces its presence by publishing an “online” status message, while also defining a “last will” message that the broker will automatically send as “offline” if the connection is lost unexpectedly. The ESP32 subscribes to a specific topic for LED control commands so that it can receive JSON payloads over MQTT, parse them, and then acknowledge each command by publishing a confirmation message back to a separate acknowledgment topic. This creates a two-way communication channel where the device can be controlled remotely and confirm successful execution of commands.
At the same time, the ESP32 regularly publishes telemetry data through MQTT. It sends heartbeat messages with uptime, signal strength, and network information, and it transmits environmental sensor readings from the BME680 to a designated topic as JSON data. All MQTT communication uses Quality of Service level 1 to ensure that messages are delivered at least once, providing reliable data exchange between the device and the broker. The code also manages automatic reconnection with exponential backoff, meaning it gracefully retries connecting to the MQTT broker when disconnected without flooding the network. In essence, from the MQTT point of view, this device behaves as a resilient, bidirectional IoT client that reports data, accepts remote commands, and maintains a persistent, reliable session with the broker.
Click here to access your code for this example.
Test it out using this link.