Publish multiple message in one topic

I want to publish multiple message like First Name, Last Name and AGE in one topic "ID"

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

char First_Name[ ] = {"ROCKY"};
const char* Last_name = "stevan";
int AGE  = 20;

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(172, 16, 0, 100);
IPAddress server(172, 16, 0, 2);

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

EthernetClient ethClient;
PubSubClient client(ethClient);

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("outTopic","hello world");

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

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(1500);
}

void loop()
{
  client.publish("ID", ); // I need help in this line 
  
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

How can we Publish multiple message in one topic ?

If you want to publish multiple data items in a single message then take a look at the sprintf() function

char message[60];
sprintf(message, "%s, %s, %d\n", First_Name, Last_name, AGE);
client.publish("outTopic", message);
1 Like

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