Sprintf() and String:format() not working as expected


#1

Hi guys, this is the last test I managed to do before my second DK died on me.

this simplle code yields wrong results ( it works perfectly on the particle photon)

#include “math.h”
#include “application.h”

double soc,volts,temp,rh,pressure;
char data[255];

void setup()
{

}

void loop() {

if (millis() % 10000 < 1000) {
temp = 25.54;
rh = 70.77;
pressure = 960.789;
soc = 95.50;
volts = 4.11;

sprintf(data,"%4.1f,%3.0f,%4.0f,%3.0f,%3.1f",temp,rh,pressure,soc,volts);

Particle.publish(“temp”,String(temp),60,PRIVATE);
delay(1000);
Particle.publish(“rh”,String(rh),60,PRIVATE);
delay(1000);
Particle.publish(“mPa”,String(pressure),60,PRIVATE);
delay(1000);
Particle.publish(“Volts”,String(volts),60,PRIVATE);
delay(1000);
Particle.publish(“SOC”,String(soc),60,PRIVATE);
delay(1000);
Particle.publish(“data”,data,60,PRIVATE);
delay(1000);
Particle.publish(“data_2”,String::format("%4.1f,%3.0f,%4.0f,%3.0f,%3.1f",temp,rh,pressure,soc,volts));
delay(1000);
}

System.sleep(SLEEP_MODE_CPU);

}

here is the output from the particle dashboard

Any thoughts ?


#2

Anythng? Anyone?
it is an odd behavior


#3

I have verified this is a bug and opened an issue in GitHub: https://github.com/bluzDK/bluzDK-firmware/issues/23

In the meantime, you could use String(double, int decimalPlaces=6); to get the desired effect, so the following works:

String msg = String(temp,2) + ‘,’ + String(rh,2) + “,” + String(pressure,3) + “,” + String(soc,2) + “,” + String(volts,2);

Particle.publish(“data”, msg);

I will update this thread when the issue is fixed


#4

Is there a more efficient way to do this? Or at least a way that doesn’t use up text space? I just switched from String() to sprintf because I was getting overflow errors from the compiler. That worked but then I remembered why I was using String() in the first place :frowning:


#5

This is still an open issue and one I hope to get to in the next release. The last version took way longer than expected due to issues with upgrading, but that is hopefully behind us now, so I hope to roll out some quick releases to clean up issues like this.

Have you tried using the String() method with the latest v2.0.50-beta.5? This opened up flash space and may allow it to work.


#6

Yea, that was going to be my next step; I didn’t see that post until after I had converted everything to sprintf.