How to convert int to string on Arduino?

前端 未结 9 1346
-上瘾入骨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:19

    The solution is much too big. Try this simple one. Please provide a 7+ character buffer, no check made.

    char *i2str(int i, char *buf){
      byte l=0;
      if(i<0) buf[l++]='-';
      boolean leadingZ=true;
      for(int div=10000, mod=0; div>0; div/=10){
        mod=i%div;
        i/=div;
        if(!leadingZ || i!=0){
           leadingZ=false;
           buf[l++]=i+'0';
        }
        i=mod;
      }
      buf[l]=0;
      return buf;
    }
    

    Can be easily modified to give back end of buffer, if you discard index 'l' and increment the buffer directly.

提交回复
热议问题