Skip to content
CommunicationMITv2.8

PubSubClient

by Nick O'Leary

PubSubClient is the de-facto standard MQTT client for Arduino-family boards, handling the MQTT packet framing, keep-alive pings, and pub/sub protocol over any network `Client` object (WiFiClient, EthernetClient, WiFiClientSecure). You give it a broker address, a `Client`, and a callback function for incoming messages, and it takes care of the wire protocol. The catch that trips people up most is the default MQTT_MAX_PACKET_SIZE of 128 bytes — publishing a JSON payload larger than that silently fails unless you increase it by defining `MQTT_MAX_PACKET_SIZE` before including the header. You also need to call `client.loop()` on every Arduino loop iteration or incoming messages and keep-alives stop being processed.

Installation

Arduino IDE — Library Manager

Sketch → Include Library → Manage Libraries → search PubSubClient

PlatformIO

lib_deps = knolleary/PubSubClient

Supported boards

Arduino UnoESP32STM32 Blue Pill

Examples

Connect and subscribe to a topic

Baseline MQTT connection pattern used across ESP32/ESP8266 IoT builds on this site.

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

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  WiFi.begin("ssid", "password");
  while (WiFi.status() != WL_CONNECTED) delay(500);
  client.setServer("broker.hivemq.com", 1883);
}

void loop() {
  if (!client.connected()) {
    client.connect("esp32Client");
    client.subscribe("solderhub/test");
  }
  client.loop();
}

Handling incoming messages

The callback fires whenever a subscribed topic receives a new message.

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

// in setup(): client.setCallback(callback);