I want to publish numeric value to MQTT but cannot workout conversion dataype

My project is to retrieve the sensor data and publish it to the MQTT topic. But when trying to publish to MQTT I’m hitting a data conversion issue. The problem line of code is below (line 3):

  int responss;
  //This doesn't actually work
  client.publish("Topic", responss);

What data type is the publish() function expecting as the second parameter ?

If you are using the PubSubClient library (you don’t say) then here are the function prototypes

   boolean publish(const char* topic, const char* payload);
   boolean publish(const char* topic, const char* payload, boolean retained);
   boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
   boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
   boolean publish_P(const char* topic, const char* payload, boolean retained);
   boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);

Note that none of them take an int as the second parameter. Does it work if you use the itoa() function to convert your int to a C style string as used in the first function variant ?

Note that you can use a pointer to an int as the second parameter

MQTTclient.publish( topicInsidePM, String(dustDensity).c_str() );

@ Idahowalker

Did you forget to add the smiley ?

1 Like

void loop() {
Serial.begin(19200);
byte poll = {0xAF, 0xFC, 0xFE, 0x40};
Serial.write(poll, sizeof(poll));
delay(3000);
int x = 6;

while(x > 0)
{
responss = Serial.read();
//Serial.print(“output =”);
Serial.println(responss, HEX);
delay(500);
x–;
}
Serial.end();
}
“This is sensor coding where I retrieve the data from sensor”
void reconnect() {

// Loop until we’re reconnected

Serial.println();
while (!client.connected()) {
Serial.print(“Attempting MQTT connection…”);
// Attempt to connect
if (client.connect(“ESP8266Client”)) {
Serial.println(“connected”);
// Once connected, publish an announcement…
client.publish(“Topic”, responss);
// … 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);
}
}
“This is code where I want to publish the sensor data but when I put variable other than const char it gives error”
Please tell me what to do?

What is syntax of client.publish() ?

Are you using the PubSubClient library ?

The punblish() function is overloaded which means that there are several variants available each with their own required parameters, as listed in my post. The version that runs depends on the parameters that you provide

Yes, I am using the PubSubClient library. I posted the code above have a look on it. and answer my query. Thanks

It would help if you posted the complete sketch so that variable declarations were included. For instance, how is responss declared ?

Please Auto format your code in the IDE, use Copy for forum in the IDE and paste it here so that it is code tags to make it easier to read and copy for examination

mqtt_esp8266_1.ino (2.6 KB)
This is complete sketch. Have a look on it

Which post is the complete code in ?

mqtt_esp8266_1.ino (2.6 KB)
This is complete code

Sorry, I misunderstood what you were saying and with the new software did not spot the attachment

Thanks

It is better to Auto format your code in the IDE, use Copy for forum in the IDE and paste it here so that it is code tags to make it easier to read and copy for examination. Please do that in future

As to your problem, try this but no guarantees that it works

      // Once connected, publish an announcement...
      char dataArray[10];  //an array to put the data in
      sprintf(dataArray, "%d", responss); //turn the data into a C string
      client.publish("Topic", dataArray);  //publish the data
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

int respons;
int responss;

//  network setting.

const char* ssid = "hamid";
const char* password = "3214774136";
const char* mqtt_server = "broker.mqtt-dashboard.com";

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

void setup() {

  Serial.begin(19200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

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.begin(19200);

  }

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

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

}

void reconnect() {

  // Loop until we're reconnected

  Serial.println();
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      char dataArray[10]; //an array to put data in
      sprintf(dataArray, "%d", responss); //turn the data into a C string
      client.publish("Topic", dataArray); //publish the data
      //delay(3000);
      // ... 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);
    }
  }
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  //respons = Serial.read();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    Serial.print("Publish message: ");
    Serial.println(respons);
    //client.publish("Topic", "sensor");
  }
  // sensor programming
  Serial.begin(19200);
  byte poll[] = {0xAF, 0xFC, 0xFE, 0x40};
  Serial.write(poll, sizeof(poll));
  delay(3000);
  int x = 6;

  while (x > 0)
  {
    responss = Serial.read();
    //Serial.print("output =");
    Serial.println(responss, HEX);
    delay(500);
    x--;
  }
  Serial.end();
  //resetFunc();
}

Thanks for the help @UKHeliBob . I need little more help as this code will publish single value on MQTT Box and I want to publish multiple values. Attached is picture of MQTTBox where 1 single value is publish. Need help to publish more than 1 value.

Ends up there was a reason I left it off.

    responss = Serial.read();

As written responss will only ever contain a single character. Do you mean that you want to send a larger value ?

To add to that, the only place in the code that you publish the value is in the reconnect() function and you only call that after finding that the client is not connected. Is that deliberate ?

A more logical flow would seem be to read the user input and if there is something to publish then go ahead and publish it having tested that the client is connected and to reconnect if it isn’t

As written “responss” will only ever contain a single character. Do you mean that you want to send a larger value ?

I want to publish multiple values as sensor gives 2 output values shown in serial monitor. Moreover in the image above a single value is display. I want to publish 2 values there. Help me in this regard.

I am lost as to which 2 values you want to publish. Which are they ?

If you can get the 2 values,each in a different variable then you can use sprintf() to format them into a single char array, together with any text required, then publish that

Alternatively you use sprintf() with one of them, publish it then use sprintf() again with the second one and publish that

If you can get the 2 values, each in a different variable then you can use sprintf() to format them into a single char array, together with any text required, then publish that
I used only one variable int = responss; and byte poll[] = {0xAF, 0xFC, 0xFE, 0x40}; is used to give command to poll the sensor. I used this responss to publish the data on MQTTBox