MQTT library PubSubClient - sending float/int/bool data to topics? char convert

I'm new MQTT. I'm looking at an example MQTT sketch from the PubSubClient library. It looks like this:

void callback(char* topic, byte* payload, unsigned int length) { // handle message arrived }

EthernetClient ethClient; PubSubClient client(server, 1883, callback, ethClient);

void setup() { Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { client.publish("outTopic","hello world"); client.subscribe("inTopic"); } }

I'd like to publish ints, bools, and floats instead of the string "hello world" to the topic, but trying this gives me a "invalid conversion from int to char" error:

void setup() { int mydata = 4; Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { client.publish("outTopic", mydata); client.subscribe("inTopic"); } }

Does the protocol only take in character strings? I have a feeling I have to do some kind of conversion involving the "&" operator...but I'm not sure.

Might've found the answer here:

// publish light reading every 5 seconds if (millis() > (time + 5000)) { time = millis(); String pubString = "{"report":{"light": "" + String(lightRead) + ""}}"; pubString.toCharArray(message_buff, pubString.length()+1); //Serial.println(pubString); client.publish("io.m2m/arduino/lightsensor", message_buff); }

In this example, rightRead is an int. The other parts of the message_buff are part of how this particular person is using the data, but the important part is this:


So this String() function converts whatever is sent to it as a parameters into a string.

Thank you for posting this here is an example built using your string conversion idea

Mqtt_Esp8266_Dhtv2.ino (4.57 KB)