Skip to main content
November 14, 2021
Question

Why does sprintf not work with RTOS?

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)

This topic has been closed for replies.

7 replies

MM..1
Super User
November 14, 2021

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

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

November 14, 2021

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.

November 14, 2021

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
November 15, 2021

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""."
November 17, 2021

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.

November 17, 2021

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
November 17, 2021

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