Question

I'm doing an Arduino sketch and I'm trying to gain some space. I saw on some websites that it's better to use sprintf than print. I tried but it takes way more space.

For example :

  char toWrite[18];
  sprintf(toWrite,"%d/%d/%d %d:%d:%d",RTC.now().day(),RTC.now().month(),RTC.now().year()-2000,RTC.now().hour(),RTC.now().minute(),RTC.now().second());
  tft.println(toWrite);

takes more space than :

  tft.print(RTC.now().day(), DEC);
  tft.print('/');
  tft.print(RTC.now().month(), DEC);
  tft.print('/');
  tft.print(RTC.now().year(), DEC);
  tft.print(' ');
  tft.print(RTC.now().hour(), DEC);
  tft.print(':');
  tft.print(RTC.now().minute(), DEC);
  tft.print(':');
  tft.println(RTC.now().second(), DEC);
  tft.println();

Could someboby explain me why ?

Many thanks !

PS : Sorry for my English, it's not my mother tongue =)

Was it helpful?

Solution

The routine sprintf is larger because it is a more complicated (and more flexible) routine than print. You can make your code smaller by having more arduous print statements. Unfortunately, there is no free lunch in this case.

OTHER TIPS

You can really cut down printf if you remove the extraneous formats.
Here is an example alternate fprintf (printf is just fprintf with 1 as first arg) that compiles down to 1/2kb including my conversion functions (it could be smaller if you remove more)

void myfprintf_(int fd,int nargs, ...){ 
   va_list ap; va_start(ap, nargs); static char *s; const char *fmt; 
   fmt=va_arg(ap, char *); 
   int i=0,p; 
   char buf[80]; 
while (fmt[i]){ 
   p=0; 
   while (fmt[i]!='%' && fmt[i]!=0) buf[p++]=fmt[i++]; 
   if (p != 0) write(fd,buf,p); 
   if (nargs-->0){ 
      switch (fmt[++i]) { 
      case 's': s=va_arg(ap, char *); break; 
      case 'd': s=dtos(va_arg(ap, int)); break; 
      case 'x': s=dtox(va_arg(ap, int),'a'); break; 
      case 'X': s=dtox(va_arg(ap, int),'A' ); break; 
      case 'f': s=ftos(va_arg(ap, double)); break; 
      case 'c': buf[0]=(va_arg(ap, int));buf[1]=0;s=buf;break; 
      case '%': s="%"; break; 
      default : s="";break; 
      } write(fd,s,strlen(s)); 
   } 
i++; 
} 
va_end(ap); 
}

just comment out the formats you won't need and modify for your existing conversion functions - Also if you want it to be more compliant, make it an int function vs void and sum the returns of write for the return value ... though 99% of the time I don't use printf's return.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top