MQTT (PubSubClient) - Leveraging as a function

Hello,
I would rate my coding skills as more of a novice and I am struggling with the MQTT client.
My need is to call a function when a port changes (high/low) and post a message to a MQTT topic.

I have used the 'mqtt_basic' example and integrated it in to my sketch and it works but it basically a static topic.
What I can't figure out without replicating the code block (close to 30 times, which I dont want to do) is how to call the function that posts a message (reconnect) with a payload in this case a string value would suffice.

Below is the standard function and I can call it with a reconnect();

void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect("arduinoClient")) {
          Serial.println("connected");
          // Once connected, publish an announcement...
          client.publish("stat/ArduinoMega2560","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);
          
        }
      }
}

I have tried calling it with reconnect(VAR_NAME)

And modifying the function to start with

void reconnect(String foo)

Obviously this didnt work.

Help would be appreciated.

Show the full code of your attempt

You might need to pass a char * instead of a String
If client is not a global variable you need to pass it by reference as well to your function

We would like to see the whole skecth.

You call reconnect() from loop() to make sure that you are still connected to the MQTT broker, which shouldn't happen often. The publish in reconnect() is just a courtesy.

Once you are connected you can call client.connect() anywhere in your loop.

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