Can not send numerical output to MQTT Server [SOLVED]

Hi,

I am trying to make a simple cpunter and send numerical variables to MQTT Server.
On serial monitor I see the counters datas fine but on MQTT Screen I see them as mixed characters. (Attached)

The code is below

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
void subscribeReceive(char* topic, byte* payload, unsigned int length);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 202);
const char* server = "192.168.1.117";
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
int counter;
void setup()
{  
counter = 0;
Serial.begin(9600);
Ethernet.begin(mac, ip);              
delay(3000);                          
mqttClient.setServer(server, 1883);   
if (mqttClient.connect("My Counter")) 
{ Serial.println("Connected"); mqttClient.setCallback(subscribeReceive);} 
else 
{ Serial.println("NOT Connected"); }
}

void loop()
{
mqttClient.loop();
mqttClient.subscribe("Counter 1");
if(mqttClient.publish("Counter 1", counter ))
{ Serial.println("Mesaj Sent"); }
else
{ Serial.println("Mesaj NOT Sent :("); }
delay(1000);
}

void subscribeReceive(char* topic, byte* payload, unsigned int length)

{
counter ++; 
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
{ Serial.println(counter); }
}

I guess INT data type is not valid with mqttClient.publish command.
What is the way for getting the significant output on server screen?
Thaks in advance

your image |500x395

I guess INT data type is not valid with mqttClient.publish command.

kind of. You can either transform your int into a cString and publish the ASCII text corresponding to your number or publish a binary version in which case you need to pass the address of the memory buffer (& of your int) and the number of bytes (sizeof your int)

Solved the problem with the code below

int counter;
counter = 0;
char ccounter[5];
String str(counter);
str.toCharArray(ccounter,5);

Thanks so much for your help.
Cheers
:slight_smile: