cancel
Showing results for 
Search instead for 
Did you mean: 

sprintf doesn't work well to show float (I already added -u _printf_float in linker options)

Jordi Becares
Associate II

Hi all,

I have a problem to show float numbers via sprintf, I'm working with STM32F334

I did a program to print via serial the voltage read from ADC, in float format like %4.2f, the problem is that the first time the sprintf generate a valid string with decimal separator, but the next iterations not.

I followed the tip recommended for @Hae Ryon Jung​  in this entry of forum, but I didn't get a good result

https://community.st.com/s/question/0D50X00009XkYaySAF/how-to-print-float-value-with-printf-in-truestudio-

Any idea?

This is the code:

adcVal = HAL_ADC_GetValue(&hadc1);
adcRes = adcVal*3.3/4096;
sprintf(buffTmp, "[%d]ADC %d %4.2f V\n\r", (int) counter, (int)adcVal, adcRes);

This is the output:

[0]ADC 2531 2.04 V
[1]ADC 2493 204 V
[2]ADC 2495 204 V

Thanks for your support

Regards

Jordi

10 REPLIES 10
AVI-crak
Senior

Use printo (...), https://bitbucket.org/AVI-crak/sprint.

Recognizes: "text", double, float, uint (8-16-32-64) _t, int (8-16-32-64) _t in any sequence.

The magic "[% d] ADC% d% 4.2f V \ n \ r" is not required.

printo ("ADC", counter, ((float) adcVal / 1024.0f), "V \n");

Jordi Becares
Associate II

Hi AVI-crack,

thanks for your feedback.

But, I think (and hope) that the same sprintf integrated in Atollic has to support it, I don't want to add more libraries (keep small footprint, and manteinable code)

Regards

Jordi

AVI-crak
Senior

They have different weight, printo is much lighter.

john doe
Lead

remove nano.specs from your linker options

Jordi Becares
Associate II

Hi John,

thanks for your feedback.

But it doesn't work.

I remove nano.spec from linker and I get the same, even worst result. The text area increase aprox 3KB, and RAM 1KB, and output is still wrong .

Regards

Jordi

AVI-crak
Senior

Jordi Becares

Delete is not required. The built-in libraries contain optimized zero-level code for the ARM core, such as hardware multiplication, division, floating point operations, and so on. The part of the library that is not used is removed from the final layout of the firmware. It is enough not to use heavy functions. (find and delete any use).

But the information on ram / rom size increase looks strange. I had the opposite.

Use optimization level 02 or higher.

Jordi Becares
Associate II

Hi,

I'm using Optimize for size(-Os).

I dont' fix the error yet. The sprintf of float number is not working well.

Any idea?

Regards

Jordi

AVI-crak
Senior

I can not repeat the mistake.

I always get the correct floating point printing for sprintf (), printf (), and my printo ().

In your case, there is a magic change in the type of the variable, possibly outside the visible code.

Jordi Becares
Associate II

What uC are you using?

Please, could you attach your project? So, I will check in my board

Thanks

Jordi