# ESP8266-01 won't connect to HiveMQ Cloud (MQTT)

**URL:** <https://community.hivemq.com/t/esp8266-01-wont-connect-to-hivemq-cloud-mqtt/2573>\
**Category:** HiveMQ Cloud\
**Created:** [December 21, 2023, 2:07pm UTC](https://community.hivemq.com/t/esp8266-01-wont-connect-to-hivemq-cloud-mqtt/2573 "2023-12-21T14:07:10Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Denisucu55](https://avatars.discourse-cdn.com/v4/letter/d/d6d6ee/32.png) [@Denisucu55](https://community.hivemq.com/u/Denisucu55)\
**Post date:** [December 21, 2023, 2:07pm UTC](https://community.hivemq.com/t/esp8266-01-wont-connect-to-hivemq-cloud-mqtt/2573/1 "2023-12-21T14:07:10Z")

</div>

Hello.  
I have been trying for a while to connect my ESP8266-01 to the Cloud, through MQTT. My eESP module is connected through serial communication to an Arduino UNO board, but I bypassed the Arduino board so I can work only with the ESP module.  
The ESP module connects to the local WiFi with success, and the MQTT communication works as well.  
I get an error rc=-2, which would correspond to some issues related to the client ID. I double checked the username, password, port and address of my cloud. I will attach the simple code I’ve been trying.  
Any help is crucial and very much appreciated!  
Thank you!

```auto
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "TP-Link_11F8";
const char* password = " ********";
const char* mqtt_broker = " *********************.s1.eu.hivemq.cloud";
const char* mqtt_username = "test123";
const char* mqtt_password = " *****";
const int mqtt_port = 8883;

WiFiClientSecure espClient;
PubSubClient client(espClient);

static const char *root_ca PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDV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bk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

void setup() {
  Serial.begin(74880);
  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi...");
    if (WiFi.status() == WL_CONNECT_FAILED) {
      Serial.println("Connection failed. Check credentials.");
      while (1) delay(1000); // Stuck here if WiFi connection fails
    }
  }

  Serial.println("Connected to WiFi");
  client.setServer(mqtt_broker, mqtt_port);

  while (!client.connected()) {
    Serial.println("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) { // **The code fails here**
      Serial.println("Connected to MQTT");
    } else {
      Serial.print("Failed to connect to MQTT, rc="); // **This is printed infinitely**
      Serial.print(client.state());
      Serial.println(" Retrying in 5 seconds");
      delay(5000);
    }
  }
}

void loop() {
  if (!client.connected()) {
    Serial.println("MQTT disconnected. Reconnecting...");
    reconnect();
  }
  client.loop();
}

void reconnect() {
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi connection lost. Reconnecting...");
    setup(); // Re-attempt WiFi connection if lost
  }
  
  while (!client.connected()) {
    Serial.println("Attempting MQTT reconnection...");
    if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
      Serial.println("Reconnected to MQTT");
    } else {
      Serial.print("Reconnection failed, rc=");
      Serial.print(client.state());
      Serial.println(" Retrying in 5 seconds");
      delay(5000);
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![Diego](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Diego](https://community.hivemq.com/u/Diego)\
**Post date:** [December 22, 2023, 11:25am UTC](https://community.hivemq.com/t/esp8266-01-wont-connect-to-hivemq-cloud-mqtt/2573/2 "2023-12-22T11:25:59Z")

</div>

Hello @Denisucu55

Welcome to HiveMQ Community! I wanted to share with you a basic sample for the ESP8266 that I’ve personally used on my device. This sample is designed to provide you with a clear understanding of how to effectively connect and publish a message to HiveMQ Cloud, so you can adapt the code to your needs.

```auto
/*
 Basic sample of connecting ESP8266 with HiveMQ Cloud 

  - Time has to be obtained from NTP, because of CA expiration date validation.
 
 It connects to HiveMQ Cloud broker then:
  - Publishes "Hello World!" to the topic "testTopic" every two seconds.
  - Subscribes to the topic "testTopic", printing out any messages (string payload) it receives.

 It will reconnect to the server if the connection is lost using a blocking reconnect function.
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

//---- WiFi settings
const char* ssid = "TYPE_WiFi_SSID";
const char* password = "TYPE_WiFi_PASSWORD";

//---- HiveMQ Cloud Broker settings
const char* mqtt_server = "TYPE_YOUR_HIVEMQ_CLOUD_URL";
const char* mqtt_user = "TYPE_YOUR_USERNAME";
const char* mqtt_password = "TYPE_YOUR_PASSWORD";

BearSSL::WiFiClientSecure espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

// HiveMQ Cloud Let's Encrypt CA certificate (hardcoded)
static const char ca_cert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)EOF";

void setClock()
{
  configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");

  Serial.print("Waiting for NTP time sync: ");
  time_t now = time(nullptr);
  while (now < 8 * 3600 * 2) {
    delay(500);
    Serial.print(".");
    now = time(nullptr);
  }
  Serial.println("");
  struct tm timeinfo;
  gmtime_r(&now, &timeinfo);
  Serial.print("Current time: ");
  Serial.print(asctime(&timeinfo));
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

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

void reconnect() {
  char err_buf[256];
  
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // MQTT client ID
    String clientId = "ESP8266Client";
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("testTopic", "Hello World!");
      // ... and resubscribe
      client.subscribe("testTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      espClient.getLastSSLError(err_buf, sizeof(err_buf));
      Serial.print("SSL error: ");
      Serial.println(err_buf);
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(ca_cert);
  espClient.setTrustAnchors(serverTrustedCA);
  setup_wifi();
  setClock(); // Required for X.509 validation
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "Hello World! #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("testTopic", msg);
  }
}

```

 ![2023-12-22 at 11.16.43@2x](https://canada1.discourse-cdn.com/flex035/uploads/hivemq1/original/1X/0047e616f0230c9705130373f79feb72e0375e50.png)

Kind regards,  
Diego from HiveMQ Team

---

<div class="post-metadata">

**Author:** ![Denisucu55](https://avatars.discourse-cdn.com/v4/letter/d/d6d6ee/32.png) [@Denisucu55](https://community.hivemq.com/u/Denisucu55)\
**Post date:** [December 22, 2023, 8:43pm UTC](https://community.hivemq.com/t/esp8266-01-wont-connect-to-hivemq-cloud-mqtt/2573/3 "2023-12-22T20:43:24Z")

</div>

The changes in code solved the issue for me. It might have been some problems related to the certifications.  
Thank you so much for the answer, Diego!
