15 January 2018

(SOLVED) Cypress PSOC5LP Failure to Format sprintf Floats

The default behaviour of Creator 4.1 is to skip processing of floating point variables for ARM based processors.  This is due to the newlib-nano library from ARM and Creator project build settings.  If you do not need to format floats then the default settings will save valuable flash space.  However, this gotcha is likely to trip the unsuspecting as good code will not perform as expected.

To following demonstration code does not perform as expected:

#include "project.h"
#include <stdio.h>
int main(void)
{
    CyGlobalIntEnable; /* Enable global interrupts. */

    float num = 12.35;
    char msg[20];

    for(;;)
    {
        sprintf(msg,"Test:%f",num);
    }
}

Adding a breakpoint and running the code with a local variable watch results in the msg char array is inspected:


This would result in an output of: "Test:" followed by a NULL '\000' if the string were transmitted.  This is not is expected or wanted.

The Solution

Some reconfiguartion is needed.  The Linker settings can be found under Project > Build Settings:


Change the Use newlib-nano Float Formating to TRUE.

To account for this change the size of the heap needs to increase.  The heap size can be set within the System tab under Design Wide Resources in the Project tree:


Increase Heap size to 0x200 bytes.

Re-build the project and the output of sprintf is now as expected:



I hope this resolves any difficulties you may be experiencing.  Enjoy!

PS. If your code doesn't appear to be working make sure you are using floating point arithmetic and using constants in their floating point form: 10.0, 1.5, 0.35 etc.

No comments:

Post a Comment