Can't connect esp8266 to MQTT Broker

hi i'm new to arduino and i have some problem adding MQTT connection from our (me and friends) arduino code.

#include <Arduino.h>
#include <math.h>
#include <Wire.h>  
#include <SPI.h>
#include <ESP8266WiFi.h>
#include "MAX30100_PulseOximeter.h"
#include <LiquidCrystal_I2C.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ThingSpeak.h>

#define REPORTING_PERIOD_MS     1000
LiquidCrystal_I2C lcd(0x27, 16,2);
PulseOximeter pox;
uint32_t tsLastReport = 0;

float spo;
float bpm;
int counter;
int motor = D7;
int solenoid = D6;
int dataadc;
int tombol = D4;
int tombolx;
int hitung;
float vol;
float mmhg;
float mmhgx;
float sistole;
float diastole;
int sistolex;
int diastolex;
int mark = 0;

const char* mqtt_server = "192.168.1.5";
const int   mqtt_port   = 1883;
const char* mqtt_user   = "user";
const char* mqtt_pass   = "123456";
 
WiFiClient espClient;
PubSubClient mqttClient(espClient); 
void onBeatDetected() {
    Serial.println("Beat!");
}

char ssid[ ] = ".....";
char pass[ ] = ".....";//password wifi
const char* server = "....";
const char* resource = ".....";
String apiKey = "....";

WiFiClientSecure clientTele;
WiFiClient client;
UniversalTelegramBot bot(".....", clientTele); // Token BOT TELEGRAM
const char* CHAT_ID = "....."; // ID obrolan untuk BOT TELEGRAM

void connectWiFi() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Menghubungkan ke");
  lcd.setCursor(0, 1);
  lcd.print("WiFi...");

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

  unsigned long startTime = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000)
  {
    delay(500);
  }

  if (WiFi.status() == WL_CONNECTED)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("WiFi Terhubung");
    Serial.println("WiFi Terhubung");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    Serial.println();
  }
  else
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Gagal Terhubung WiFi");
    Serial.println("Gagal Terhubung WiFi");
  }
}
void connectMQTT(){
   while (!mqttClient.connected()) {
    Serial.print("Connecting to MQTT broker...");
    Serial.print("Broker IP: ");
  Serial.println(mqtt_server);
  Serial.print("Broker Port: ");
  Serial.println(mqtt_port);
    
    // Attempt to connect to the MQTT broker
    if (mqttClient.connect("ESP8266Client", mqtt_user, mqtt_pass)) {
      Serial.println("connected");
      
      // Optionally subscribe to a topic if needed
      // mqttClient.subscribe("your_topic");
      
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  lcd.clear(); 
  lcd.begin();
  lcd.backlight();
  lcd.noCursor();
  Serial.begin(9600);
  Serial.println("Pulse oxymeter test!");
  pinMode(motor,OUTPUT);
  pinMode(solenoid,OUTPUT);
  pinMode(tombol,INPUT_PULLUP);
  connectWiFi();
  
  mqttClient.setServer(mqtt_server, mqtt_port);  // Set detail MQTT broker 
  connectMQTT();
  delay(2000);

  clientTele.setInsecure();

  Serial.print("Initializing pulse oximeter..");

    // Initialize sensor
    if (!pox.begin()) {
        Serial.println("FAILED");
        for(;;);
    } else {
        Serial.println("SUCCESS");
    }
    
  // Configure sensor to use 7.6mA for LED drive
  pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);

  // Register a callback routine
  pox.setOnBeatDetectedCallback(onBeatDetected);

 lcd.setCursor(0,0);
 lcd.print("BPM= ");
 lcd.setCursor(0,1);
 lcd.print("S=   D= ");
}

void loop() {
 dataadc = analogRead(A0);
 mmhgx = (dataadc - 46.222) / 3.2;
 lcd.setCursor(0,1);
 lcd.print("S= ");
 lcd.print(sistolex);
 lcd.print(" D= ");
 lcd.print(diastolex);
 lcd.print("    ");
     
 tombolx = digitalRead(tombol); 

 if(tombolx == LOW){
  mark = 0;
  lcd.clear();
  delay(1000);
  digitalWrite(motor,HIGH);
  digitalWrite(solenoid,HIGH);
  mulai();
  }
    
 pox.update();  
 // Grab the updated heart rate and SpO2 levels
 if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
        bpm = pox.getHeartRate();
        spo = pox.getSpO2();
        
        lcd.setCursor(0,0);
        lcd.print("B/S: ");
        lcd.print(pox.getHeartRate());
        lcd.print(" / ");
        lcd.print(pox.getSpO2());
        lcd.print("    ");
        
        // Serial.print("Heart rate:");
        // Serial.print(pox.getHeartRate());
        // Serial.print("bpm / SpO2:");
        // Serial.print(pox.getSpO2());
        // Serial.println("%");
        
        tsLastReport = millis();
    }
 mqttClient.loop();
delay(10); 
}

void mulai(){
  
 dataadc = analogRead(A0);
 mmhg = (dataadc - 46.222) / 3.2;

if((mmhg >= mmhgx + 2)&&(mmhg > 142)&&(mark == 0)){
//digitalWrite(motor,LOW); 
Serial.println("SISTOLE"); 
sistole = mmhg;
mark = 2; 
digitalWrite(motor,LOW);
}

if((mmhg >= mmhgx + 2)&&(mmhg > 50)&&(mmhg < 105)&&(mark == 2)){
//digitalWrite(motor,LOW); 
Serial.println("DIASTOLE"); 
diastole = mmhg;
mark = 3;
}

 lcd.setCursor(0,1);
 lcd.print("S= ");
 lcd.print(mmhg);
 lcd.print("     ");

if(mmhg >= 150)
{
 digitalWrite(motor,LOW);   
}

mmhgx = mmhg;

Serial.println(mmhg);

if((mark == 3)&&(mmhg < 50)){
lcd.clear();
delay(1000);
mark = 0;
sistolex = sistole;
diastolex = diastole;
digitalWrite(solenoid,LOW);
kirimtele();
kirimthings();
kirimmqtt();
Serial.print(" ");
return;  
}

if((mark == 2)&&(mmhg < 50)){
lcd.clear();
delay(1000);
mark = 0;
sistolex = sistole;
diastolex = random(60,90);
digitalWrite(solenoid,LOW);
kirimtele();
kirimthings();
Serial.println("");
return;  
}

delay(1); 
mulai();  
}

void kirimtele(){
  bool success = false;
  String pesanLCD = "";

  if ((sistolex >= 90 )&&(sistolex <= 139)) {
    Serial.println("TENSI NORMAL");
    pesanLCD = "TENSI NORMAL";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(1500);
    
    String tensi = " tensi sekarang : ";
    tensi += float(sistolex);
    tensi += " / ";
    tensi += float(diastolex);
    tensi += " \n";
    tensi += "TENSI NORMAL!\n";
    success = bot.sendMessage(CHAT_ID, tensi, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if ((sistolex >= 140 )&&(sistolex <= 170)) {
    Serial.println("TENSI TINGGI");
    pesanLCD = "TENSI TINGGI";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String tensi = " tensi sekarang : ";
    tensi += float(sistolex);
    tensi += " / ";
    tensi += float(diastolex);
    tensi += " \n";
    tensi += "TENSI TINGGI!\n";
    success = bot.sendMessage(CHAT_ID, tensi, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if ((sistolex >= 50 )&&(sistolex <= 90)) {
    Serial.println("TENSI RENDAH");
    pesanLCD = "TENSI RENDAH";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String tensi = " tensi sekarang : ";
    tensi += float(sistolex);
    tensi += " / ";
    tensi += float(diastolex);
    tensi += " \n";
    tensi += "TENSI RENDAH!\n";
    success = bot.sendMessage(CHAT_ID, tensi, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if ((bpm >= 50 )&&(bpm <= 100)) {
    Serial.println("BPM NORMAL");
    pesanLCD = "BPM NORMAL";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String bpmnya = " BPM sekarang : ";
    bpmnya += float(bpm);
    bpmnya += " \n";
    bpmnya += "BPM NORMAL!\n";
    success = bot.sendMessage(CHAT_ID, bpmnya, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if ((bpm >= 100 )&&(bpm <= 200)) {
    Serial.println("BPM CEPAT");
    pesanLCD = "BPM CEPAT";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String bpmnya = " BPM sekarang : ";
    bpmnya += float(bpm);
    bpmnya += " \n";
    bpmnya += "BPM CEPAT!\n";
    success = bot.sendMessage(CHAT_ID, bpmnya, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if ((bpm >= 10 )&&(bpm <= 90)) {
    Serial.println("BPM LAMBAT");
    pesanLCD = "BPM LAMBAT";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String bpmnya = " BPM sekarang : ";
    bpmnya += float(bpm);
    bpmnya += " \n";
    bpmnya += "BPM LAMBAT!\n";
    success = bot.sendMessage(CHAT_ID, bpmnya, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if (spo >= 95 ) {
    Serial.println("Saturasi NORMAL");
    pesanLCD = "SPO NORMAL";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String sponya = " SPO sekarang : ";
    sponya += float(spo);
    sponya += " \n";
    sponya += "Saturasi NORMAL!\n";
    success = bot.sendMessage(CHAT_ID, sponya, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }

  if (spo < 95 ) {
    Serial.println("Saturasi RENDAH");
    pesanLCD = "SPO RENDAH";
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(pesanLCD);
    delay(2000);
    
    String sponya = " SPO sekarang : ";
    sponya += float(spo);
    sponya += " \n";
    sponya += "Saturasi RENDAH!\n";
    success = bot.sendMessage(CHAT_ID, sponya, "");
    Serial.print("Mengirim data sensor ke telegram");
    Serial.println(" ");
  }
  
  // Menampilkan pesan keberhasilan di LCD
  lcd.clear();
  lcd.setCursor(0,0);
  if (success) {
    lcd.print("Data Berhasil");
    lcd.setCursor(0,1);
    lcd.print("Ke Telegram");
  } else {
    lcd.print("Gagal Kirim");
    lcd.setCursor(0,1);
    lcd.print("Ke Telegram");
  }
  delay(2000);  // Biarkan pesan di layar selama 2 detik
  lcd.clear();   // Hapus pesan dari layar
}


void kirimthings() {
    bool success = false;  // Variabel untuk mengecek apakah pengiriman berhasil

    if (client.connect(server, 80)) {
        // String data yang akan dikirim
        String postStr = "field1=" + String(bpm) + "&field2=" + String(spo) + "&field3=" + String(sistolex) + "&field4=" + String(diastolex);

        Serial.print("Sending data: ");
        Serial.println(postStr);

        // Kirim HTTP request ke ThingSpeak
        client.print(String("POST ") + resource + apiKey + " HTTP/1.1\r\n" +
                     "Host: " + server + "\r\n" +
                     "Connection: close\r\n" +
                     "Content-Type: application/x-www-form-urlencoded\r\n" +
                     "Content-Length: " + postStr.length() + "\r\n\r\n" +
                     postStr);

        Serial.println(". Data sent to ThingSpeak.");
        success = true;  // Set success menjadi true jika koneksi dan pengiriman berhasil
    } else {
        Serial.println("Failed to connect to ThingSpeak.");
    }
    client.stop();

    // Menampilkan pesan di LCD
    lcd.clear();
    lcd.setCursor(0, 0);
    if (success) {
        lcd.print("Data Berhasil");
        lcd.setCursor(0, 1);
        lcd.print("Ke ThingSpeak");
    } else {
        lcd.print("Gagal Kirim");
        lcd.setCursor(0, 1);
        lcd.print("Ke ThingSpeak");
    }
    delay(2000);  // Tampilkan pesan di layar selama 2 detik
    lcd.clear();  // Hapus pesan dari layar setelahnya

    Serial.println("Waiting...");
}

void kirimmqtt() {
    while (!mqttClient.connected()) {
        Serial.print("Connecting to MQTT broker at ");
        Serial.print(mqtt_server);
        Serial.print(":");
        Serial.println(mqtt_port);
        // Attempt to connect
        if (mqttClient.connect("ESP8266Client", mqtt_user, mqtt_pass)) {
            Serial.println("connected");

            // Prepare data strings to publish
            String systolicMsg = String(sistolex);  // Systolic value
            String diastolicMsg = String(diastolex);  // Diastolic value
            String bpmMsg = String(bpm);  // Heart rate (BPM)
            String spo2Msg = String(spo);  // Oxygen saturation (SpO2)

            // Publish data to corresponding MQTT topics
            mqttClient.publish("healthmonitor/systolic", systolicMsg.c_str());
            mqttClient.publish("healthmonitor/diastolic", diastolicMsg.c_str());
            mqttClient.publish("healthmonitor/bpm", bpmMsg.c_str());
            mqttClient.publish("healthmonitor/spo2", spo2Msg.c_str());
 
            Serial.println("Data sent to MQTT broker.");
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Data Berhasil");
            lcd.setCursor(0,1);
            lcd.print("Ke Broker MQTT");
            delay (3500);
            lcd.clear();
        } else {
            Serial.print("failed, rc=");
            Serial.print(mqttClient.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("MQTT Send Failed");
            lcd.setCursor(0, 1);
            lcd.print("Retrying...");
            
            delay(5000);
        }
    }
}

so this code is using Lolin (wemos) D1 R2 & mini as a board. i compile it and upload it. it succeed but the serial monitor or device end up looping with this message.

connecting to MQTT broker...failed, rc=-2 try again in 5 seconds

so this is the parts i didnt understand:
1.went the device (192.168.1.xxx) connected with my laptop (192.168.1.5) i can ping them fine using cmd and it had an activity that those 2 ips is connected.
2. i tried check my MQTT broker using mqqtx and mqtt explorer. the broker can connect and communicate just fine.
3. but went i checked the mosquito log there's no log about the device try to connect to broker.

p.s :

  1. i already tried the code without mqtt stuff, the device work as intended.
  2. english is my 3rd language.

Welcome to the forum

const char* mqtt_server = "192.168.1.5";

When using an IP address for the server declare the server address in this way

IPAddress mqtt_server(192, 168, 1, 5);

rather than

const char* mqtt_server = "192.168.1.5";

i changed it, the loop still exist.

Sorry but I don't think that I can be of any more help with you sketch. I cannot compile your code because I don't have all the libraries

I suggest that you try one of the examples from the PubSubClient library to eliminate any possiblity of clashes with your other libraries

for now i reduce the lenght of the code by removing connect to thingspeak and telegram bot. the full code is down below:

#include <PubSubClient.h>
#include <Arduino.h>
#include <math.h>
#include <Wire.h>
#include <ESP8266WiFi.h>
#include "MAX30100_PulseOximeter.h"
#include <LiquidCrystal_I2C.h>

#define REPORTING_PERIOD_MS 1000
LiquidCrystal_I2C lcd(0x27, 16, 2);
PulseOximeter pox;
uint32_t tsLastReport = 0;

float spo;
float bpm;
int motor = D7;
int solenoid = D6;
int dataadc;
int tombol = D4;
int tombolx;
int mark = 0;
float mmhg;
float mmhgx;
float sistole;
float diastole;
int sistolex;
int diastolex;

char ssid[] = "Pyotatoast";
char pass[] = "Easypeasy01";  // WiFi password
IPAddress mqtt_server(192, 168, 1, 5);

WiFiClient espClient;
PubSubClient client(espClient);

void connectWiFi() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Menghubungkan ke");
  lcd.setCursor(0, 1);
  lcd.print("WiFi...");

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

  unsigned long startTime = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - startTime < 10000) {
    delay(500);
  }

  if (WiFi.status() == WL_CONNECTED) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("WiFi Terhubung");
    Serial.println("WiFi Terhubung");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    Serial.println();
  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Gagal Terhubung WiFi");
    Serial.println("Gagal Terhubung WiFi");
  }
}

void connectMqtt() {
  while (!client.connected()) {
    Serial.print("Connecting to MQTT...");

    // Attempt to connect, using a client ID (optional username/password can be provided as well)
    if (client.connect("ESP8266Client", "user", "123456")) {  // You can change the client ID if needed
      Serial.println("connected");
      // You can subscribe to topics here if you want the device to receive messages
      // client.subscribe("your_topic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" trying again in 5 seconds");
      delay(5000);  // Wait 5 seconds before retrying
    }
  }
}

void onBeatDetected() {
  Serial.println("Beat!");
}

void setup() {
  lcd.clear();
  lcd.begin();
  lcd.backlight();
  lcd.noCursor();
  Serial.begin(9600);
  Serial.println("Pulse oximeter test!");

  pinMode(motor, OUTPUT);
  pinMode(solenoid, OUTPUT);
  pinMode(tombol, INPUT_PULLUP);
  
  connectWiFi();

  client.setServer(mqtt_server, 1883);
  connectMqtt();

  Serial.print("Initializing pulse oximeter...");

  // Initialize sensor
  if (!pox.begin()) {
    Serial.println("FAILED");
    for (;;);
  } else {
    Serial.println("SUCCESS");
  }

  // Configure sensor to use 7.6mA for LED drive
  pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);

  // Register a callback routine
  pox.setOnBeatDetectedCallback(onBeatDetected);

  lcd.setCursor(0, 0);
  lcd.print("BPM= ");
  lcd.setCursor(0, 1);
  lcd.print("S=   D= ");
}

void loop() {
  if (!client.connected()) {
    connectMqtt();  // Reconnect to MQTT if disconnected
  }
  client.loop();  // Keep the connection alive

  dataadc = analogRead(A0);
  mmhgx = (dataadc - 46.222) / 3.2;
  lcd.setCursor(0, 1);
  lcd.print("S= ");
  lcd.print(sistolex);
  lcd.print(" D= ");
  lcd.print(diastolex);
  lcd.print("    ");

  tombolx = digitalRead(tombol);

  if (tombolx == LOW) {
    mark = 0;
    lcd.clear();
    delay(1000);
    digitalWrite(motor, HIGH);
    digitalWrite(solenoid, HIGH);
    mulai();
  }

  pox.update();
  // Grab the updated heart rate and SpO2 levels
  if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
    bpm = pox.getHeartRate();
    spo = pox.getSpO2();

    lcd.setCursor(0, 0);
    lcd.print("B/S: ");
    lcd.print(pox.getHeartRate());
    lcd.print(" / ");
    lcd.print(pox.getSpO2());
    lcd.print("    ");

    String systolicStr = String(sistolex);
    String diastolicStr = String(diastolex);
    String bpmStr = String(bpm);
    String spoStr = String(spo);

    client.publish("health/systolic", systolicStr.c_str());
    client.publish("health/diastolic", diastolicStr.c_str());
    client.publish("health/bpm", bpmStr.c_str());
    client.publish("health/spo2", spoStr.c_str());

    tsLastReport = millis();
  }

  delay(10);
}

void mulai() {
  dataadc = analogRead(A0);
  mmhg = (dataadc - 46.222) / 3.2;

  if ((mmhg >= mmhgx + 2) && (mmhg > 142) && (mark == 0)) {
    Serial.println("SISTOLE");
    sistole = mmhg;
    mark = 2;
    digitalWrite(motor, LOW);
  }

  if ((mmhg >= mmhgx + 2) && (mmhg > 50) && (mmhg < 105) && (mark == 2)) {
    Serial.println("DIASTOLE");
    diastole = mmhg;
    mark = 3;
  }

  lcd.setCursor(0, 1);
  lcd.print("S= ");
  lcd.print(mmhg);
  lcd.print("     ");

  if (mmhg >= 150) {
    digitalWrite(motor, LOW);
  }

  mmhgx = mmhg;
  Serial.println(mmhg);

  if ((mark == 3) && (mmhg < 50)) {
    lcd.clear();
    delay(1000);
    mark = 0;
    sistolex = sistole;
    diastolex = diastole;
    digitalWrite(solenoid, LOW);
    return;
  }

  if ((mark == 2) && (mmhg < 50)) {
    lcd.clear();
    delay(1000);
    mark = 0;
    sistolex = sistole;
    diastolex = random(60, 90);
    digitalWrite(solenoid, LOW);
    return;
  }

  delay(1);
  mulai();
}

and below is my library in my sketch (p.s not all of them is for above arduino code)

My Library.

Since the problem is the same maybe the problem is in my firewall. but, idk how to manage so my board can gain access to my mqtt via wifi without making mess left and right

Personally I would remove everything except the connection to the MQTT broker and get that working first

What is the IP address of the ESP8266 ?

1 Like

As is right now is 192.168.1.3

And since the setup and loop is for hardware stuff on the board. It might be okay to leave it as it is

Have it your own way but I know what I would do

That is the biggest Library I have ever seen. I would eliminate that first, then as others have said, start small and build up.

I believe we never actually remove library since we started study in class. So that library had been like 1 year and half. So genuine question do bloated library efect arduino project much?

I will try, gonna give news if i have more trouble went i set up the code or had solution for my problems

YES. As someone with over 50 years experience, I can tell you that KISS, and divide and conquer are my mantra.
BTW, I don't do homework, bye.

Try this example

/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/

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

// Update these with values suitable for your network.

const char* ssid = "...........";
const char* password = "...........";
IPAddress mqtt_server(192, 168, 1, 112);

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

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();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  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("outTopic", msg);
  }
}

It works for me using a Pi 4 as the MQTT broker and a Weomos D1 Mini board

yeah i try using the example now my code look like this:

/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "";
const char* password = "";
IPAddress mqtt_server(192, 168, 1, 5);

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

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() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("healthmonitor/spo", "hello world");
      client.publish("healtmonitor/BPM", "selamat pagi");
      client.publish("healthmonitor/sistol", "guten tag");
      // ... and resubscribe
      client.subscribe("healtmonitor");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  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("outTopic", msg);
  }
}

and below is the serial monitor

WiFi connected
IP address: 
192.168.1.3
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

i kinda fell like i does something wrong here but it still the same went i upload into my board but now the device start having like a long noise like wheeerrrrr without stoping

Which device is making the noise ?

my arduino which is LOLIN(WEMOS) D1 R2 & mini

There is nothing on that board that should make a noise. What have you got connected to it ?

By the way, the code that you posted works for me

if my code work on your, what's seem to be the problem then? i'm confused

somekind of solenoid, lcd crsytal, blood pressure sensor, and some kind of heart sensor

Disconnect everything from the board and try your code again

there's actually fatal mistake that i made, the board is already become device that connected together and already had a case. so kinda hard to remove them

Post a schematic of your project, and I do not mean a 'photo, showing all the devices, how they are connected and how they are powered

Make sure that the schematic that you post matches what you have built rather than what you intended to build