Timers+floats+sprintf=SOS hard fault

I saw there was a bit of trouble a while back (~ a year ago?) with printf and floats. Seems like this was fixed. using printfs in loop() or setup() with a float, no problem.

But when I try todo this with a timer, I get an SOS with a single flash. Am I doing something wrong? or did I step on a bug? It seems the workaround for typecasting to a string does resolve the problem, but curious if this is a different printf/float issue? Running this on last RC code and 0.5.3 firmware yield same SOS.

void print_every_second()
{
    char msg[255];
    float floatVar = 0.01;   // our readings
    sprintf(msg, "%0.2f", floatVar);
}

Timer timer(1000, print_every_second);

void setup()
{
    Serial.begin(9600);
    timer.start();
    Serial.println("setup() - complete");
}

You need to be aware that software timer callback functions run in their own thread which has a considerably smaller stack allowance than your normal app code.
So reserving 255bytes on the stack to start with, takes a good chunk away from that and then calling sprintf() which in turn will need some stack might be just too much.
Try reducing your msg to about 16bytes and see then.

2 Likes

Thanks! and good to know about stack size!

2 Likes