0
0
AutocadHow-ToBeginner · 4 min read

How to Use MQTT with Arduino: Simple Guide and Example

To use MQTT with Arduino, connect your Arduino to a network using WiFi or Ethernet, then use the PubSubClient library to connect to an MQTT broker. You publish and subscribe to topics to send and receive messages between devices.
📐

Syntax

The basic syntax involves including the PubSubClient library, setting up a network client (WiFi or Ethernet), and creating an MQTT client object. You then connect to the MQTT broker using client.connect(), subscribe to topics with client.subscribe(), and publish messages with client.publish().

Key parts:

  • PubSubClient client(networkClient); - creates MQTT client using your network connection
  • client.connect(clientID); - connects to the MQTT broker
  • client.subscribe(topic); - listens for messages on a topic
  • client.publish(topic, message); - sends a message to a topic
  • client.loop(); - keeps connection alive and processes messages
arduino
#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "yourSSID";
const char* password = "yourPassword";
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void setup() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  client.setServer(mqttServer, mqttPort);
  client.connect("ArduinoClient");
  client.subscribe("test/topic");
}

void loop() {
  if (!client.connected()) {
    client.connect("ArduinoClient");
  }
  client.loop();
  client.publish("test/topic", "Hello MQTT");
  delay(2000);
}
💻

Example

This example connects an Arduino with WiFi to a public MQTT broker, subscribes to a topic, and publishes a message every 2 seconds. It prints received messages to the Serial Monitor.

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

const char* ssid = "yourSSID";
const char* password = "yourPassword";
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("ArduinoClient")) {
      client.subscribe("test/topic");
    } else {
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  client.publish("test/topic", "Hello MQTT from Arduino");
  delay(2000);
}
Output
Message arrived on topic: test/topic Message: Hello MQTT from Arduino
⚠️

Common Pitfalls

  • Not calling client.loop() regularly causes lost messages and disconnects.
  • Forgetting to set the MQTT server with client.setServer() prevents connection.
  • Using wrong WiFi credentials stops network connection.
  • Not handling reconnects causes the client to stop working after disconnect.
  • Publishing too fast can overwhelm the broker or network.
arduino
// Wrong: Missing client.loop()
void loop() {
  if (!client.connected()) {
    client.connect("ArduinoClient");
  }
  client.publish("test/topic", "Hello");
  delay(1000);
}

// Right: Include client.loop()
void loop() {
  if (!client.connected()) {
    client.connect("ArduinoClient");
  }
  client.loop();
  client.publish("test/topic", "Hello");
  delay(1000);
}
📊

Quick Reference

  • Include libraries: #include <WiFi.h> and #include <PubSubClient.h>
  • Connect WiFi: WiFi.begin(ssid, password);
  • Set MQTT server: client.setServer(mqttServer, mqttPort);
  • Connect MQTT: client.connect(clientID);
  • Subscribe: client.subscribe(topic);
  • Publish: client.publish(topic, message);
  • Keep alive: client.loop();

Key Takeaways

Use the PubSubClient library to handle MQTT on Arduino easily.
Always call client.loop() inside loop() to maintain connection and receive messages.
Handle WiFi and MQTT reconnects to keep your device online.
Publish and subscribe to topics to communicate with other MQTT clients.
Test with public brokers like broker.hivemq.com before using private ones.