ESP8266 doesn't recieve message from MQTT

I tried using this code but for some reason the ESP doesn't recieve a message from MQTT, here the code that i use:

#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
#include "NTP.h"
#include <WiFiUdp.h>

const int buttonPin = D7;
int buttonState = 0;
#define MQTT_HOST "***********"
#define MQTT_PORT ****

#define RelayPin1 D3
#define RelayPin2 D4
#define RelayPin3 D5
#define RelayPin4 D6

#define MQTT_SUB_Relay1 "esp-wemos-mini/2/relay1"
#define MQTT_SUB_Relay2 "esp-wemos-mini/2/relay2"
#define MQTT_SUB_Relay3 "esp-wemos-mini/2/relay3"
#define MQTT_SUB_Relay4 "esp-wemos-mini/2/relay4"

#define MQTT_PUB "esp-wemos-mini/2/data"

#define SEALEVELPRESSURE_HPA (1013.25)

WiFiUDP wifiUdp;
NTP ntp(wifiUdp);

WiFiManager wm;

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

Adafruit_BME280 bme;
float temperature = 0;
float humidity = 0;
float barometer = 0;

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

  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  setup_wifi();
  client.setServer(MQTT_HOST, MQTT_PORT);
  client.setCallback(callback);

  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(RelayPin1, OUTPUT);
  pinMode(RelayPin2, OUTPUT);
  pinMode(RelayPin3, OUTPUT);
  pinMode(RelayPin4, OUTPUT);

  digitalWrite(RelayPin1, HIGH);
  digitalWrite(RelayPin2, HIGH);
  digitalWrite(RelayPin3, HIGH);
  digitalWrite(RelayPin4, HIGH);

  ntp.begin();
  ntp.timeZone(7,0);
}

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

  Serial.println("Connecting to Wi-Fi...");

  WiFi.mode(WIFI_STA);

  bool res;

  res = wm.autoConnect("Test","password");

  if(!res) {
        Serial.println("Failed to connect");
        // ESP.restart();
    } 
    else {
        //if you get here you have connected to the WiFi    
        Serial.println("connected");
    }

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

void configModeCallback(WiFiManager *myWiFiManager)
// Called when config mode launched
{
  Serial.println("Entered Configuration Mode");
 
  Serial.print("Config SSID: ");
  Serial.println(myWiFiManager->getConfigPortalSSID());
 
  Serial.print("Config IP Address: ");
  Serial.println(WiFi.softAPIP());
}

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


  if (String(topic) == MQTT_SUB_Relay1) {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("RelayPin 1 ON");
      digitalWrite(RelayPin1, LOW);   // Turn the LED on (Note that LOW is the voltage level
    }
    else if(messageTemp == "off"){
      Serial.println("RelayPin 1 Off");
      digitalWrite(RelayPin1, HIGH);  // Turn the LED off by making the voltage HIGH
    }
  }
  if (String(topic) == MQTT_SUB_Relay2) {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("RelayPin 2 ON");
      digitalWrite(RelayPin2, LOW);   // Turn the LED on (Note that LOW is the voltage level
    }
    else if(messageTemp == "off"){
      Serial.println("RelayPin 2 Off");
      digitalWrite(RelayPin2, HIGH);  // Turn the LED off by making the voltage HIGH
    }
  }
  if (String(topic) == MQTT_SUB_Relay3) {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("RelayPin 3 ON");
      digitalWrite(RelayPin3, LOW);   // Turn the LED on (Note that LOW is the voltage level
    }
    else if(messageTemp == "off"){
      Serial.println("RelayPin 3 Off");
      digitalWrite(RelayPin3, HIGH);  // Turn the LED off by making the voltage HIGH
    }
  }
  if (String(topic) == MQTT_SUB_Relay4) {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("RelayPin4 ON");
      digitalWrite(RelayPin4, LOW);
    }
    else if(messageTemp == "off"){
      Serial.println("RelayPin4 OFF");
      digitalWrite(RelayPin4, HIGH);
    }
  }
}
void(* resetFunc) (void) = 0;
void button() {
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if(buttonState == LOW) {

    Serial.println("Restarting");
    wm.resetSettings();
    resetFunc();
    delay(1000);
  }
  
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
 Serial.println("MQTT connected");
 if (client.connect("Alphamas")){
    Serial.print("Attempting MQTT connection...");
    
      client.subscribe(MQTT_SUB_Relay1);
      client.subscribe(MQTT_SUB_Relay2);
      client.subscribe(MQTT_SUB_Relay3);
      client.subscribe(MQTT_SUB_Relay4);
 }else{
   Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);

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

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now; 
    ntp.update();
    temperature = bme.readTemperature();   
    // Uncomment the next line to set temperature in Fahrenheit 
    // (and comment the previous temperature line)
    //temperature = 1.8 * bme.readTemperature() + 32; // Temperature in Fahrenheit
    
    // Convert the value to a char array
    char tempString[8];
    dtostrf(temperature, 1, 2, tempString);
    Serial.print("Temperature: ");
    Serial.println(tempString);

    humidity = bme.readHumidity();
    
    // Convert the value to a char array
    char humString[8];
    dtostrf(humidity, 1, 2, humString);
    Serial.print("Humidity: ");
    Serial.println(humString);

    barometer = bme.readPressure() / 100.0F;
    
    // Convert the value to a char array
    char baroString[8];
    dtostrf(barometer, 1, 2, baroString);
    Serial.print("Barometer: ");
    Serial.println(baroString);

    Serial.print("Time: ");
    Serial.println(ntp.formattedTime("%Y/%m/%d %T"));

    char messageData[60];
    sprintf(messageData, "%s, %s, %s, %s",ntp.formattedTime("%Y/%m/%d %T"),tempString,humString,baroString);
    client.publish(MQTT_PUB, messageData, true); 
    delay(20000);
    
  }
  button();
}

Thanks

Is the callback() function ever called ?

Please post your full sketch so that the problem can be seen in context

I already change the code,

Thank you

What about my question ?

i think i already called it on void setup()
client.setCallback(callback)

get rid of this annoying delay as It obstructs client.loop() from running as fast as It can within a loop

and you might increase your publishing interval to 20 seconds ?

  if (now - lastMsg > 20000UL) {
1 Like

You have told the program which function to call when a message is received, but if you don't receive a message then it will not actually be called

Do you ever see "Message arrived on topic: " in the Serial monitor ?

Now i see it, KASSIMSAMJI told me to remove that delay now the ESP Recieve a massage
image_2024-05-06_143125858

Thanks, now the ESP recieve a massage

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