Function in C that converts an integer to a string

48 Views Asked by At

I've been trying to create a function that converts an integer to a string and returns the string. At this moment it randomly "mixes" the returned strings. Please note that I intentionally don't use:

  • sprintf as it slows down the microcontroller dramatically (clock 1MHz) so I can't use it;
  • itoa only, as I need to convert an int16 to string that represents a rounded value of an angle, e.g. "359.9". Below is the fragment of code which causes the problem. Is there anything that could fix it? I've tried various methods - none of them worked... I'm aware that after executing this function loses the returned string. If the STR_OUT is not static then it outputs nothing. Thanks.

Code:

char *STR1;
char *STR2;
    
unsigned int16 VAL1 = 1111;
unsigned int16 VAL2 = 2222;

char *func(unsigned int16 NUM
{
   static char STR[6];
   itoa(NUM, 10, STR);
   
   return STR;
}

void main ();
{
   STR1 = func(VAL1);
   STR2 = func(VAL2);

   fprintf (USB, "%s", STR1);  //shows randomly "1111" or "2222"
   fprintf (USB, "%s", STR2);  //shows randomly "1111" or "2222"
}
0

There are 0 best solutions below