cancel
Showing results for 
Search instead for 
Did you mean: 

Why does sprintf not work with RTOS?

Not applicable

I'm trying to use this function:

char str[80];
float val;
 
sprintf(str, "%f", val);

But the task freezes.

I've already added the -u _printf_float flag to work with the serial output, but it still doesn't work.

If using another form of variable, %d, %u, %lu, %s works fine.

The task also freezes when trying to print the log through the serial port similar to the method used for USB debugging.

(Using CMSIS_V1)

7 REPLIES 7
MM..1
Chief II

When you add -u swith to linker config try define prec

sprintf(str, "%.6f", val);

Not applicable

Thanks, but it didn't work. And actually I was already using %.4f I don't know if it should work like %.6f, but it doesn't work either.

Not applicable

Maybe it's faster for me to do it differently than figure out what's going on, it's going to be more work, but I think I'll have to separate the decimal and insert it separately into the string.

TDK
Guru

sprintf uses the heap, possibly a failed or overlapping allocation. Could also be a stack overflow.

If you feel a post has answered your question, please click "Accept as Solution".
Not applicable

Thanks for the help, but it didn't work out yet.

I increased the Heap from 400 to 4000 and the Stack from 200 to 4000, it still didn't work, it kept freezing.

Not applicable

If I don't use %f then it works. I separated the decimal part from the whole part (Integer), so it worked, it didn't freeze anymore. ¯\_(ツ)_/¯

float float_VAL = 12.3456;
uint8_t val_1 = float_VAL;
uint32_t val_dec = float_VAL * 10000;
char str[80] = {0};
 
val_dec -= val_1 * 10000;
 
sprintf(str, "%d.%04lu", val_1, val_dec);

NEdom.1
Associate III

printf family is powerful and convenient with enough resources. But with limited resource in RTOS, it can be dirty.

In latest STM32CubeIDE with newlib support, printf function is working fine with proper heap, task stack size and io redirection settings. Also you need to enable Using float with printf from newlib-nano in MCU settings.

Since printf family is briefly used for debug and text processing, using a reduced embedded version is encouraged. Try this https://github.com/mpaland/printf