How to convert int to string on Arduino?

前端 未结 9 1344
-上瘾入骨i
-上瘾入骨i 2021-01-31 06:32

How do I convert an int, n, to a string so that when I send it over the serial, it is sent as a string?

This is what I have so far:

int ledP         


        
9条回答
  •  -上瘾入骨i
    2021-01-31 07:24

    Here below is a self composed myitoa() which is by far smaller in code, and reserves a FIXED array of 7 (including terminating 0) in char *mystring, which is often desirable. It is obvious that one can build the code with character-shift instead, if one need a variable-length output-string.

    void myitoa(int number, char *mystring) {
      boolean negative = number>0;
    
      mystring[0] = number<0? '-' : '+';
      number = number<0 ? -number : number;
      for (int n=5; n>0; n--) {
         mystring[n] = ' ';
         if(number > 0) mystring[n] = number%10 + 48;
         number /= 10;
      }  
      mystring[6]=0;
    }
    

提交回复
热议问题