Serial.print array problem

Hi,

I got into the following problem:

I'm trying to get a temperature from a DS1820 sensor and send it over Virtualwire but something's worng and I don't know what. Below the section with the problem:

  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  char mesg[100] = { sprintf(mesg, "%g", tempC) };
Serial.println(mesg);

First I want to verify if is there anything in the mesg array, but it's empty.
I've checked the output of the "sensors.getTempCByIndex(0)" and it's ok, I get temperature in Celsius degrees in the following format: 21.12
I found the "sprintf" transformation on the internet.

What's wrong, what am I missing?

Thanks in advance,
BR,
CC

char mesg[100] = { sprintf(mesg, "%g", tempC) };

This is not how to use sprintf;

char mesg[100];
sprintf(mesg, "%g", tempC);

is how to use sprintf.

However, you should be aware that the %f format is not supported on the Arduino. Therefore, neither are %e or %g.

Hi,

Thanks a lot Paul for the answer.

How would you deal with this kind of issue?
As you saw I'm not a C++ guru.
Just let me know your thoughts.

BR,
CC

I would split the float into two integers.

int wholeTempC = tempC; // The whole part
int fracTempC = (tempC - wholeTempC) * 1000; // The fractional part * 1000

Then, I'd print the whole part, a decimal point, and the fractional part, with leading 0s as required, to fill 3 places.

sprintf(mesg, "%d.%3d", wholeTempC, fracTempC);

Paul,

I suspect that he'll want to use a slightly different format:sprintf(mesg, "%d.%03d", wholeTempC, fracTempC);so that the fractional part is zero filled.

Regards,

-Mike

I was just looking at the %d format this morning. The page I was looking at said that if the precision value was larger than required to hold the value, it was left filled with 0. I had thought it was left filled with 0, and that the 0 was required to change the left fill character.

I just went back and looked, and saw that I left out the dot. The format specifier should be %.3d. The width comes before the decimal point, and requires the 0 to left fill. The precision comes after the decimal point, and automatically left fills with 0.

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Hi,

Thanks a lot for the answers.
I'll do some tests and come back to you.

BR,
CC

Hi guys,

It worked.
I made few modifications to fit my needs and now everything it's ok excepting that on subzero temperatures the integer and the decimal has the minus sign in front like this: -12.-24 :slight_smile:
I think there's a simple workaround for this.

Thanks a lot for all your precious help.
CC

excepting that on subzero temperatures the integer and the decimal has the minus sign in front like this: -12.-24 Smiley
I think there's a simple workaround for this.

Sure. Just use the absolute value of the temperature to compute wholeTempC and fracTempC, then negate wholeTempC if tempC is negative.