Failed to Connect to MQTT broker using ESP8266

Please help me, i should finish this project as soon
I want to make project monitoring using ESP8266, MQTT, and Node-RED dashboard
but I have an issue that my serial monitors showing cannot connected to MQTT
"Failed to connect to MQTT broker, rc=-2"
I try to test my mqtt in CMD using Sub and Pub, i send some text and it works well. but in my project it's failed.
here is my code:

#include <Wire.h>
#include <Adafruit_MLX90614.h>
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Replace with your Wi-Fi credentials
const char* ssid = "mywifi";
const char* password = "password";

// Replace with your MQTT broker IP address
const char* mqttServer = "127.0.0.1";
const int mqttPort = 1883;

// Replace with your MQTT topics
const char* mqttTopicTemp = "sensors/temperature";
const char* mqttTopicOxygen = "sensors/oxygen";

WiFiClient espClient;
PubSubClient client(espClient);

Adafruit_MLX90614 mlx = Adafruit_MLX90614();
PulseOximeter pox;

void onHeartRateBeatDetected()
{
  float hr = pox.getHeartRate();
  Serial.print("Heart rate:");
  Serial.println(hr);
}

void setup() {
  Serial.begin(115200);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("Connected to WiFi");
  
  // Connect to MQTT broker
  client.setServer(mqttServer, mqttPort);
  
  while (!client.connected()) {
    if (client.connect("ESP8266Client")) {
      Serial.println("Connected to MQTT broker");
    }
    else {
      Serial.print("Failed to connect to MQTT broker, rc=");
      Serial.println(client.state());
      delay(2000);
    }
  }

  // Initialize sensors
  mlx.begin();
  pox.begin();

  // Set up a callback for pulse detection
  pox.setOnBeatDetectedCallback(onHeartRateBeatDetected);
}

void loop() {
  // Read temperature from MLX90614 sensor
  float temperature = mlx.readObjectTempC();
  
  // Convert temperature to string
  String tempPayload = String(temperature);
  
  // Publish temperature to MQTT topic
  client.publish(mqttTopicTemp, tempPayload.c_str());

  // Update pulse oximeter
  pox.update();

  // Read oxygen level from MAX30100 sensor
  if (pox.begin()) {
    float oxygen = pox.getSpO2();
  
    // Convert oxygen level to string
    String oxygenPayload = String(oxygen);
  
    // Publish oxygen level to MQTT topic
    client.publish(mqttTopicOxygen, oxygenPayload.c_str());
  }

  delay(1000);  // Adjust the delay based on your needs
}

Welcome to the forum

What is the address of machine running the MQTT server ?

const char* mqttServer = "127.0.0.1";

seems to imply that it is running on the ESP8266

1 Like

I actually don't know where can i get the MQTT IP server, but i'm pretty sure that's the correct IP. because i tried to send a simple message using MQTT in terminal and it works well.


or u can tell me where can i get the MQTTserver correctly?

127.0.0.1 is the localhost address - it refers to the computer that the command is running on.

So, when you say 127.0.0.1 on your PC, it refers to your PC;
when you say 127.0.0.1 in your sketch, it refers to the device the sketch is running on.

If you want your sketch to use the MQTT server that's running on your PC, then your sketch will need to contain the IP address of your PC.

The comment tells you that you needed to replace that IP address!

Did you also update the other details?

You should also be able to use a DNS name:

WiFi - client.connect() - Arduino Reference.

Yes i also opened my node-red with that localhost ip, my node-red ip is 127.0.0.1:1880
so should i put 127.0.0.1 in my MQT server int the code code?

i do update all the details what it should be including the MQTT topics
here is what i sketch on my node-red flow


image

is there anything incorrect? thank you for your response btw

Presumably you have Node RED running on your PC, then?

No.

Again, 127.0.0.1 refers to the device where it is running - so, unless your MQTT server is running on the ESP8266, you will need something else.

Your sketch needs the IP address of the system where your MQTT server is running.
If your MQTT server is running on your PC, then that will be the IP address of your PC.

You can get the IP address of your PC by typing ipconfig at a command prompt on that PC.

Thank you,
i tried to change MQTT server on the code using:

  1. 127.0.0.1 which is the localhost
  2. 192.168.18.4 which is my IPv4 address on ipconfig
    but it still resulting the same error

Is your ESP8266 actually on the same network as your PC?

Have you tried a simple sketch on the ESP8266 to ping your PC?

Have you looked up what that rc value actually means?

Is your ESP8266 actually on the same network as your PC?
Yes
since the code has function

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

it always showing connected to wifi

Have you tried a simple sketch on the ESP8266 to ping your PC?

Have you looked up what that rc value actually means?

There are a lot of pieces to this project you have to get working independently first before putting it altogether.

I would recommend you get your mosquitto broker running, set up a publisher and client on the same machine and get that working. This is without node-red and arduino. That gets the mqtt broker working. Then get node-red working with the broker. Set up node-red as a client and use the same publisher. Once you get that working get the arduino involved.

I took me a good few days to understand and getting all that to work when I first used mqtt.
Good luck, it will take some time.

Edit: Didn't realize last post was 2 months ago.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.