What is wrong with this code? (MQTT)

plese help me:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "Arduino.h"
#include <Servo.h>

Servo servoObject1;
Servo servoObject2;
Servo servoObject3;

const char* ssid ="xxxxxxxxx";
const char* password ="xxxxxxxxxx";
const char* mqtt_server ="192.168.178.33";
const int mqtt_port =1886;

WiFiClient espClient;
PubSubClient client(espClient);

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

WiFi.begin(ssid, password);

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

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

void MQTTCallback(char* topic, byte* payload, unsigned int length) {
String Command = "";

for (int i = 0; i < length; i++) {
Command = Command + (char)payload[i];
}
int angle = Command.toInt();

if(strcmp(topic, "ServoControl/Servo1/Angle") == 0)
{
servoObject1.write(angle);
}

if(strcmp(topic, "ServoControl/Servo2/Angle") == 0)
{
servoObject2.write(angle);
}

if(strcmp(topic, "ServoControl/Servo3/Angle") == 0)
{
servoObject3.write(angle);
}
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");

// Create a random client ID
String clientId = "ServoControl";

// Attempt to connect
if (client.connect(clientId.c_str())) {
  Serial.println("connected");

  client.subscribe("ServoControl/Servo1/Angle");
  client.subscribe("ServoControl/Servo2/Angle");
  client.subscribe("ServoControl/Servo3/Angle");
}
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(115200);

servoObject1.attach(D2);
servoObject2.attach(D3);
servoObject3.attach(D4);

setup_wifi();
client.setServer(mqtt_server, mqtt_port);
reconnect();
client.setCallback(MQTTCallback);
}

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

Arduino: 1.8.13 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

C:\Users\Michael\Downloads\iobroker_servocontrol_release\iobroker_servocontrol_Orgi\iobroker_servocontrol_Orgi.ino: In function 'void loop()':

iobroker_servocontrol_Orgi:104:19: error: 'connectToMQTT' was not declared in this scope

 connectToMQTT();

               ^

Mehrere Bibliotheken wurden für "Servo.h" gefunden

Benutzt: C:\Users\Michael\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\Servo

Nicht benutzt: C:\Arduino\libraries\Servo

Nicht benutzt: C:\Users\Michael\Documents\Arduino\libraries\Servo

exit status 1

'connectToMQTT' was not declared in this scope

Dieser Bericht wäre detaillierter, wenn die Option
"Ausführliche Ausgabe während der Kompilierung"
in Datei -> Voreinstellungen aktiviert wäre.

Hi @peter_ko

What is the problem? We need some info in order to help you.

Also, when posting code, please use the "</>" icon in the editor on the top bar. (Paste all of the code inside of the " ``` " icons.)

Thanks for the help.
The MQTT connection breaks off after a while.

That should be the solution but I can't get it to work.

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

The problem is described on this page:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "Arduino.h"
#include <Servo.h> 

Servo servoObject1; 
Servo servoObject2; 
Servo servoObject3; 

const char* ssid = "<wlan-ssid>";
const char* password = "<wlan-pwd>";
const char* mqtt_server = "<iobroker-ip>";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

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

  WiFi.begin(ssid, password);

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

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

void MQTTCallback(char* topic, byte* payload, unsigned int length) {
  String Command = "";

  for (int i = 0; i < length; i++) {
    Command = Command + (char)payload[i];
  }  
  int angle = Command.toInt();

  if(strcmp(topic, "ServoControl/Servo1/Angle") == 0)
  {
    servoObject1.write(angle); 
  }

  if(strcmp(topic, "ServoControl/Servo2/Angle") == 0)
  {
    servoObject2.write(angle); 
  }

  if(strcmp(topic, "ServoControl/Servo3/Angle") == 0)  
  {
    servoObject3.write(angle); 
  }    
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
 
    // Create a random client ID
    String clientId = "ServoControl";

    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");

      client.subscribe("ServoControl/Servo1/Angle");
      client.subscribe("ServoControl/Servo2/Angle");
      client.subscribe("ServoControl/Servo3/Angle");
    }
    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(115200);

  servoObject1.attach(D2); 
  servoObject2.attach(D3); 
  servoObject3.attach(D4); 

  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  reconnect();
  client.setCallback(MQTTCallback);  
}

void loop()
{
  client.loop();
}

Can you help me?

Has it been considered that the issue with the MQTT connection could be with the network connection?

Here is my ESP32 freeRTOS code that checks for WiFi connection then calls client.loop() to extend the MQTT connection.

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

The MQTT callback is doing to much work. I seperate my MQYY callback rpcessing from parsing the incoming.

void IRAM_ATTR mqttCallback(char* topic, byte * payload, unsigned int length)
{
  memset( x_message.payload, '\0', payloadSize ); // clear payload char buffer
  x_message.topic = ""; //clear topic string buffer
  x_message.topic = topic; //store new topic
  int i = 0; // extract payload
  for ( i; i < length; i++)
  {
    x_message.payload[i] = ((char)payload[i]);
  }
  x_message.payload[i] = '\0';
  xQueueOverwrite( xQ_Message, (void *) &x_message );// send data to queue
} // void mqttCallback(char* topic, byte* payload, unsigned int length)

The MQTT callback only retrieves the MQTT info and packages the data to be sent to the parser.

Could you rebuild my program so that it works?
The problem is I'm just as bad at English as I am at programming.
I let google translate everything.
If you help me I would be very grateful

You could post in the German section. (That way, no google translate needed.)

The english part is bigger. I was hoping that I could be helped here.

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