How to connect to HiveMQ Cloud from Arduino

I’m trying to make connection to HiveMQ cloud from Arduino, but get a connection failed with state “-2”. In the cluster details only ports 8883 (TLS) and 8884 (Websocket + TLS) are specified, but all the Arduino examples seem to use port 1883, e.g. Arduino PubSubClient - MQTT Client Library Encyclopedia.

The network I use is a WiFi defined as

#include <WiFiNINA.h>

// WiFi settings
char ssid[] = "***";          
char ssid_password[] = "***";  
int wifi_status = WL_IDLE_STATUS;

WiFiClient network;

void setup() {
  while (wifi_status != WL_CONNECTED) {
    wifi_status = WiFi.begin(ssid, ssid_password);

I use this wifi network to connect to HiveMQ Cloud with:

#include <PubSubClient.h>

PubSubClient mqttClient(network);

const char* server = "";

void init_mqtt() {
  mqttClient.setServer(server, 1883);

  if (mqttClient.connect("Arduino", "xxx", "xxx")) {
  } else {
    Serial.print("Connection failed: ");

Serial.println(mqttClient.state()); shows the error code -2.

How can I further investigate what is going wrong? Or do I need to do additional steps to be able to connect to TLS?

Hello Frank,

You are trying to connect to HiveMQ Cloud with the default MQTT port (1883). HiveMQ Cloud only allows the ports 8883 (TLS) and 8884 (Websocket + TLS). This is why your connection fails.

Or do I need to do additional steps to be able to connect to TLS?

Yes, you do need to take further steps. Good news is that a full fledge guide on how to do this will be available very soon.
In the meantime maybe you can find some help in this thread: MQTT with SSL/TLS · Issue #462 · knolleary/pubsubclient · GitHub

  • Yannick

Thanks for the feedback! How soon is very soon? :wink:

I guess the most important part is the certificate to be added into

// Set x509 CA root (must match server cert)
const char *x509CA PROGMEM = R"EOF("

Hi Frank,

In case it help, I’m able to connect on the hiveMQ Cloud server with an arduino MKR Wifi 1010 via the library ArduinoMqttClient ( GitHub - arduino-libraries/ArduinoMqttClient: ArduinoMqttClient Library for Arduino available on the Library Manager.

1 Like

Hello Frank :wink:

How soon is very soon?

HiveMQ Cloud now has a guide on how to connect with Arduino ESP8266. You can find it under Cluster Details > Getting Started > Arduino ESP8266. I hope this helps you :slight_smile:

- Yannick


For others looking for the correct link, you need a HiveMQ Cloud account and then can find the info on{YOUR_CLOUD_ID}