How to Use MQTT with Arduino: Simple Guide and Example
To use
MQTT with Arduino, install the PubSubClient library and connect your Arduino to a Wi-Fi network. Then, use the library to connect to an MQTT broker, subscribe to topics, and publish messages using simple functions like client.connect(), client.subscribe(), and client.publish().Syntax
The basic syntax to use MQTT on Arduino involves these steps:
- Include libraries:
WiFi.hfor network andPubSubClient.hfor MQTT. - Setup Wi-Fi: Connect Arduino to your Wi-Fi network.
- Initialize MQTT client: Provide MQTT broker address and port.
- Connect to broker: Use
client.connect(clientID)to connect. - Subscribe to topics: Use
client.subscribe(topic)to listen for messages. - Publish messages: Use
client.publish(topic, message)to send data. - Loop: Call
client.loop()regularly to maintain connection and handle messages.
cpp
#include <WiFi.h> #include <PubSubClient.h> const char* ssid = "yourSSID"; const char* password = "yourPassword"; const char* mqtt_server = "broker.hivemq.com"; WiFiClient espClient; PubSubClient client(espClient); void setup_wifi() { WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } } void reconnect() { while (!client.connected()) { if (client.connect("ArduinoClient")) { client.subscribe("test/topic"); } else { delay(5000); } } } void setup() { setup_wifi(); client.setServer(mqtt_server, 1883); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); }
Example
This example connects an Arduino with Wi-Fi to a public MQTT broker, subscribes to a topic, and publishes a message every 5 seconds. It also prints received messages to the serial monitor.
cpp
#include <WiFi.h> #include <PubSubClient.h> const char* ssid = "yourSSID"; const char* password = "yourPassword"; const char* mqtt_server = "broker.hivemq.com"; WiFiClient espClient; PubSubClient client(espClient); void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("]: "); for (unsigned int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); } void setup_wifi() { delay(10); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } } void reconnect() { while (!client.connected()) { if (client.connect("ArduinoClient")) { client.subscribe("test/topic"); } else { delay(5000); } } } void setup() { Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); static unsigned long lastMsg = 0; unsigned long now = millis(); if (now - lastMsg > 5000) { lastMsg = now; const char* msg = "Hello from Arduino"; client.publish("test/topic", msg); } }
Output
Message arrived [test/topic]: Hello from Arduino
Message arrived [test/topic]: Hello from Arduino
... (repeats every 5 seconds)
Common Pitfalls
- Wi-Fi not connected: MQTT won't work without Wi-Fi. Always check
WiFi.status(). - MQTT broker unreachable: Use correct broker address and port.
- Not calling
client.loop(): This keeps the connection alive and processes messages. - Wrong topic names: Topics are case-sensitive and must match between publisher and subscriber.
- Using blocking code: Avoid long delays that stop
client.loop()from running.
cpp
/* Wrong way: Missing client.loop() causes no messages received */ void loop() { if (!client.connected()) { reconnect(); } // client.loop(); // Missing call delay(1000); } /* Right way: Always call client.loop() regularly */ void loop() { if (!client.connected()) { reconnect(); } client.loop(); delay(1000); }
Quick Reference
Remember these key functions when using MQTT with Arduino:
client.connect(clientID): Connect to MQTT broker.client.subscribe(topic): Listen to a topic.client.publish(topic, message): Send a message.client.loop(): Maintain connection and handle messages.client.setCallback(callback): Set function to handle incoming messages.
Key Takeaways
Install and include the PubSubClient library to use MQTT on Arduino.
Always connect Arduino to Wi-Fi before connecting to the MQTT broker.
Call client.loop() regularly to keep the MQTT connection alive and process messages.
Use correct topic names and broker details to avoid connection issues.
Use a callback function to handle incoming MQTT messages.