Publishing a float value with PubSubClient

I am stuck on a problem that should have an easy solution, but that I'm unable to find due to my lack of knowledge programming Arduino.

I am working with a Nano 33 IOT exchanging (publishing and receiving) messages with a MQTT broker (Ubidots in this particular case). When sending an integer value to the broker, I have no problems:

char msg_out[20];
itoa(intvalue,msg_out,10);
mqttclient.publish(topic, msg_out,retain);escribe o pega el código aquí

The problem comes when having to send a float value instead of an integer one. I cannot find any way of sending the string with the float value conversion. Function dtostrf(floatvalue,5,2,msg_out) does not work, and there is no ftoa() function doing something similar to itoa() but with float values.

Any hint about how to proceed ?

Thanks very much for your help

Joan

    bmeInfo.concat( String(x_eData.Temperature, 2) );
    bmeInfo.concat( "," );
    bmeInfo.concat( String(x_eData.Pressure, 2) );
    bmeInfo.concat( "," );
    bmeInfo.concat( String(x_eData.Humidity, 2) );
    bmeInfo.concat( "," );
    bmeInfo.concat( String(x_eData.IAQ, 2) );
    xSemaphoreGive ( sema_eData );
    xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY );
    if ( MQTTclient.connected() )
    {
      MQTTclient.publish( topicInsideInfo, bmeInfo.c_str() );
    }
    xSemaphoreGive( sema_MQTT_KeepAlive );
    xSemaphoreGive( sema_PublishPM ); // release publish of dust density

The temperature, pressure, humidity and iaq are floats.

The dtostrf() function does indeed work as documented. I suspect any difficulty you had was due to Pilot Error.

gfvalvo, thanks for your reply. You are right. The dtostrf() DID not work, and now (I don't know why) it does work (?!?). I don't understand what has happened ... but now it works:

dtostrf(t,5,2,msg_out);
if (!mqttclient.publish(pubTopicTemperature, msg_out, retain)) Serial.println("** ERROR 7 Publish");

Independently of this, following idahowalker suggestion, I have tried also:

String myString;
myString.concat(String(h));
if (!mqttclient.publish(pubTopicHumidity, myString.c_str(), retain)) Serial.println("** ERROR 8 Publish");

and this also works.

Thanks very much to both of you for your help. I have spent a complete afternoon trying to see what was going on ...

Definitely, when you are stuck on something like this, better to go out to have a walk to refresh your mind.

Once again, thanks very much.

Joan

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