Skip to main content
Graduate
February 12, 2025
Question

sprintf with %f in interrupt handler creating problem

  • February 12, 2025
  • 1 reply
  • 711 views

Dear all,

i am facing very strange problem with sprintf function .

i am using sprintf function in 1ms timer interrupt routine and it works fine. for example.

 

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
 sprintf(uDisMsg, "%.1f", 258.6);
 sprintf(lDisMsg, "%.1f", 25.3);
 printf("%s %s\n",uDisMsg,lDisMsg);
}

 

but when i call any method from while(1) loop in main function like

 

while (1)
{
 superloop();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}

 

then sprintf sometimes outputs right result sometimes outputs to 0.0

if i don't call superloop() in while(1) then sprintf works fine.

i am not able to understand what problem it faces while calling any method in while(1).


Code formatting applied - please see How to insert source code for future reference.

    This topic has been closed for replies.

    1 reply

    Super User
    February 12, 2025

    @sanju wrote:

    i am using sprintf function in 1ms timer interrupt routine .


    That's not wise at all - especially on a chip with no FPU.

    Plus you are also calling printf - is that a blocking call to output the data over a UART?

    These are really not things to be doing in an interrupt handler!

     


    @sanju wrote:

    i am not able to understand what problem it faces while calling any method in while(1).


    Probably, you just get away with it in the case with no code in the main loop ...

    sanjuAuthor
    Graduate
    February 12, 2025

    printf can be removed, that is not part of application it is just used to see output of sprintf.

    this code works on STM32F072RBT7 but doesn't work on STM32F103RBT7.

    and sprintf doesn't have any problem with %d format specifier, it only creates problem with %f.

    Super User
    February 12, 2025

    @sanju wrote:

    and sprintf doesn't have any problem with %d format specifier, it only creates problem with %f.


    As previously noted, you're on a processor with no FPU - so all floating-point stuff has to be done "manually" in software.

     


    @sanju wrote:

    this code works on STM32F072RBT7 but doesn't work on STM32F103RBT7.


    Again, it's probably marginal - you just happen to "get lucky" in one case, and not the other.

    Just don't do this in an interrupt handler!

     


    @sanju wrote:

    printf can be removed, that is not part of application it is just used to see output of sprintf.


    But none of it makes sense to be in a real application!

    What is it you're actually trying to achieve here?