Subscribe to mqtt with esp32

Hiii everyone,
I begun since a few weeks to learn how to work with mqtt on Arduino. So i have two boards( ESP32), the first one as publisher with two sensor ( a PIR MOTION SENSOR and a fire detector). The second one with a simple lcd 1602, which works as subscriber. The first is already working perfectly so my problem now is to make the second one work as i want. In the Fact, i want to subscribe to my broker and hold the published topic, and then if the content or the value of topic give me “OK” , then a message will be written on the lcd display. Here below are the two codes for my Boards, the first for the publisher and the second one for my subscriber.
I´ve tried this but it didn´t works.

The first One

# include <Arduino.h>

#include <Adafruit_Sensor.h>

# include <WiFi.h>

# include <PubSubClient.h>

// wifi Daten
const char* ssid = “zuzuu” ;
const char* password = “bu23jrYczuzur” ;
WiFiClient WifiClient ;

// MQTT Broker_Daten
const char* mqttServer = “192.168.0.220” ; // Broker-passwort
PubSubClient mqttClient( WifiClient) ;

//Topic
char FlameSate[] =“flameState”;
char Bewegung[]= “Bewegung” ;
int pirSensor= 27 ;
int ledPin = 32 ; // für meinen Bewegungsmelder
int flamePin = 34;

//Verbindung mit dem Broker herstellen
void mqttConnect()
{
Serial.print(“Verbindung zum MQTT_Server”);
Serial.print( mqttServer);
while(!mqttClient.connected())
{
Serial.print(“.”);
if (mqttClient.connect(“ES”))
{
Serial.print(“MQTT-VErbunden”);
}
else
{
Serial.print("Fehlgeschlagen ");
Serial.print(mqttClient.state());
Serial.println(“erneuter Versuch in 5 Sec”);
delay(5000);
}

}
mqttClient.subscribe(“test/esp32”);
}

void setup() {

pinMode(flamePin, INPUT); // Setze Flammensensor als Eingang
pinMode(ledPin, OUTPUT); // Setze LED als Ausgang

Serial.begin(115200);
Serial.println();
Serial.print(“Verbingsaufbaun zu”) ;
Serial.print(ssid);
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.print(“”);
Serial.println(“Wifi connected”);
Serial.print(“IP Add:”);
Serial.print(WiFi.localIP());

// Verbindung mit MQTT-Server
mqttClient.setServer(mqttServer, 1883);
[//mqttClient.setCallback](https://mqttClient.setCallback)(callback);
mqttConnect();
}

void loop() {

// Wenn der Flammensensor eine Flamme erkennt, schalte die LED ein
/* if (flameValue > 100) { // Der Schwellenwert von 100 muss möglicherweise angepasst werden
digitalWrite(ledPin, HIGH); // Schalte LED ein
} else {
digitalWrite(ledPin, LOW); // Schalte LED aus
} */

if(!mqttClient.connected())
{
mqttConnect();
}
mqttClient.loop();

int flameValue = analogRead(flamePin); // Lese analoge Spannung vom Flammensensor

if(flameValue > 100)
{
Serial.print(“Achtung Fire, Feuerwehr Anrufen !!!”);
mqttClient.publish(FlameSate, “OK”);
}
else
{
Serial.print(“Sicher, Kein Feuer !”);
mqttClient.publish(FlameSate, “Nein”);
}

int pirSensorValue = digitalRead(pirSensor);
if(pirSensorValue== HIGH)
{
digitalWrite(ledPin, HIGH) ;
Serial.print(“Bewegung erkannt”);
mqttClient.publish(Bewegung, “OK”);
delay(1000) ;
}
else
{
digitalWrite(ledPin, LOW);
Serial.print(“Keine Bewegung”);
mqttClient.publish(Bewegung, “Nein”);
delay(1000) ;

}

delay(200);
}

The Second One where help is needed

#include <Arduino.h>
#include <LiquidCrystal.h>
#include <Adafruit_Sensor.h>

#include <Wifi.h>

# include <PubSubClient.h>

// Lcd initialisierung
LiquidCrystal lcd(22,21,5,18,23,19);

// Encoder
int Clk= 33;
int Data= 25;
int SwBut = 25;
int menu =1 ;
static int LastState ;

// wifi Daten
const char* ssid = “UPC7813368” ;
const char* password = “bu23jrYctjRr” ;
WiFiClient WifiClient ;

// MQTT Broker_Daten
const char* mqttServer = “192.168.0.220” ;
PubSubClient mqttClient( WifiClient) ;

// Topic für mqtt
//Topic
char FlameSate[] =“flameState”;
char Bewegung[]= “Bewegung” ;
byte* payload;

//Verbindung mit dem Broker herstellen
void mqttConnect()
{
Serial.print(“Verbindung zum MQTT_Server”);
Serial.print( mqttServer);
while(!mqttClient.connected())
{
Serial.print(“.”);
if (mqttClient.connect(“ES”))
{
Serial.print(“MQTT-VErbunden”);
}
else
{
Serial.print(“Fehlgeschlagen, rc=”);
Serial.print(mqttClient.state());
Serial.println(“erneuter Versuch in 5 Sec”);
delay(5000);
}
}
mqttClient.subscribe(“test/esp32”);
}

//Callback Nachrichten-Empfang (Subscribe)
void callback( char* topic, byte* message, unsigned int length)
{
Serial.print("topic: ") ;
Serial.print(topic) ;

String str ;
for (int i =0 ; i< length ; i++)
{
str += (char)message[i];
}
Serial.print( "Nachrichtenempfang für topic: ");
Serial.print(topic);
Serial.print(“Nachricht :”);
Serial.println(str);
}
/*void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
Serial.print("Payload: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic, FlameSate) == 0) {
if (strcmp((char*)payload, “OK”) == 0) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.println(“OK Feuer”);
lcd.display();
}
} else if (strcmp(topic, Bewegung) == 0) {
if (strcmp((char*)payload, “OK”) == 0) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.println(“OK Bewegung”);
lcd.display();
}
}
}
*/

void setup()
{
lcd.begin(16, 2);

// Wifi Verbindung
Serial.begin(115200);
Serial.println();
Serial.print(“Verbingsaufbaun zu”) ;
Serial.print(ssid);
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.print(“”);
Serial.println(“Wifi connected”);
Serial.print(“IP Add:”);
Serial.print(WiFi.localIP());

// Verbindung mit MQTT-Server
mqttClient.setServer(mqttServer, 1883);
mqttClient.setCallback(callback);
mqttConnect();

}

void loop()
{
if (!mqttClient.connected()) {
mqttConnect();

}
// mqttClient.subscribe(Bewegung) ;
// mqttClient.subscribe(FlameSate) ;
lcd.display();
mqttClient.loop();

}

Sorry but some Part of the Code are actually written in german, so i hope you can help me to better understand how to works with mqtt. Thanks

Welcome to the forum

This is your callback() function

void callback(char* topic, byte* message, unsigned int length)
{
    Serial.print("topic: ");
    Serial.print(topic);

    String str;
    for (int i = 0; i < length; i++)
    {
        str += (char)message[i];
    }
    Serial.print("Nachrichtenempfang für topic: ");
    Serial.print(topic);
    Serial.print(“Nachricht
                 :”);
    Serial.println(str);
}

Does it print what you have published ?

Where in the sketch do you test what you have received ?

Id check that WiFi is connected before checking to see if MQTT is connected, sort of like this:

/*
  Important to not set vTaskDelay/vTaskDelayUntil to less then 10. Errors begin to develop with the MQTT and network connection.
  makes the initial wifi/mqtt connection and works to keeps those connections open.
*/
void MQTTkeepalive( void *pvParameters )
{
  sema_MQTT_KeepAlive   = xSemaphoreCreateBinary();
  xSemaphoreGive( sema_MQTT_KeepAlive ); // found keep alive can mess with a publish, stop keep alive during publish
  MQTTclient.setKeepAlive( 90 ); // setting keep alive to 90 seconds makes for a very reliable connection, must be set before the 1st connection is made.
  TickType_t xLastWakeTime = xTaskGetTickCount();
  const TickType_t xFrequency = 250; //delay for ms
  for (;;)
  {
    //check for a is-connected and if the WiFi 'thinks' its connected, found checking on both is more realible than just a single check
    if ( (wifiClient.connected()) && (WiFi.status() == WL_CONNECTED) )
    {
      xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY ); // whiles MQTTlient.loop() is running no other mqtt operations should be in process
      MQTTclient.loop();
      xSemaphoreGive( sema_MQTT_KeepAlive );
    }
    else {
      log_i( "MQTT keep alive found MQTT status % s WiFi status % s", String(wifiClient.connected()), String(WiFi.status()) );
      if ( !(wifiClient.connected()) || !(WiFi.status() == WL_CONNECTED) )
      {
        connectToWiFi();
      }
      connectToMQTT();
    }
    //log_i( " high watermark % d",  uxTaskGetStackHighWaterMark( NULL ) );
    xLastWakeTime = xTaskGetTickCount();
    vTaskDelayUntil( &xLastWakeTime, xFrequency );
  }
  vTaskDelete ( NULL );
}
////
void connectToMQTT()
{
  byte mac[5]; // create client ID from mac address
  WiFi.macAddress(mac); // get mac address
  String clientID = String(mac[0]) + String(mac[4]) ; // use mac address to create clientID
  while ( !MQTTclient.connected() )
  {
    MQTTclient.connect( clientID.c_str(), mqtt_username, mqtt_password );
    vTaskDelay( 250 );
  }
  MQTTclient.setCallback ( mqttCallback );
  MQTTclient.subscribe   ( topicOK );
  MQTTclient.subscribe   ( topicRemainingMoisture_0 );
  MQTTclient.subscribe   ( topicWindSpeed );
  MQTTclient.subscribe   ( topicWindDirection );
  MQTTclient.subscribe   ( topicDPnWI );
  MQTTclient.subscribe   ( topicOutsideTemperature );
  MQTTclient.subscribe   ( topicOutsideHumidity );
  MQTTclient.subscribe   ( topicOutsidePressure );
  MQTTclient.subscribe   ( topicRainfall );
  //MQTTclient.subscribe   ( topicWSVolts );
  MQTTclient.subscribe   ( topicPower );
} //void connectToMQTT()
void connectToWiFi()
{
  int TryCount = 0;
  while ( WiFi.status() != WL_CONNECTED )
  {
    TryCount++;
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    vTaskDelay( 4000 );
    if ( TryCount == 10 )
    {
      ESP.restart();
    }
  }
  WiFi.onEvent( WiFiEvent );
}

Instead of just assuming that WiFi is always connected.

Your void mqttConnect() function does not subscribe to a topic. If a topic is not subscribed to then how can a payload be received?

@UKHeliBob i didn't receive anything on the serial monitor.

@Idahowalker i will check what you but for `void mqttConnect() i've also tried this but so far does'nt work

void mqttConnect()
{
Serial.print("Verbindung zum MQTT_Server");
Serial.print( mqttServer);
while(!mqttClient.connected())
{
Serial.print(".");
if (mqttClient.connect("ES"))
{
Serial.print("MQTT-VErbunden");

}
else
{
  Serial.print("Fehlgeschlagen, rc="); 
  Serial.print(mqttClient.state()); 
  Serial.println("erneuter Versuch in 5 Sec"); 
delay(5000); 
}
 mqttClient.subscribe(Bewegung);

}
}

I'd be checking for a valid WiFi connection before trying to make a mqtt broker connection.

Did you use a 3rd party app like mqtt.fx to connect to your broker?

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