I've been trying to get printf() functionality which still works with the F() macro. Here's what I came up with:
void _p(boolean nl, const char *format, va_list args ){
char buf[128]; // resulting string limited to 128 chars
vsnprintf(buf, sizeof(buf), format, args);
if (nl) Serial.println(buf);
else Serial.print(buf);
}
void _p(boolean nl,const __FlashStringHelper *format, va_list args ){
char buf[128]; // resulting string limited to 128 chars
#ifdef __AVR__
vsnprintf_P(buf, sizeof(buf), (const char *)format, args); // progmem for AVR
#else
vsnprintf(buf, sizeof(buf), (const char *)format, args); // for the rest of the world
#endif
if (nl) Serial.println(buf);
else Serial.print(buf);
}
void pl(const char *format, ... ){
va_list args;
va_start (args, format );
_p(1,format,args);
va_end(args);
}
void pl(const __FlashStringHelper *format, ... ){
va_list args;
va_start(args, format );
_p(1,format,args);
va_end(args);
}
void p(const char *format, ... ){
va_list args;
va_start(args, format );
_p(0,format,args);
va_end(args);
}
void p(const __FlashStringHelper *format, ... ){
va_list args;
va_start(args, format );
_p(0,format,args);
va_end(args);
}
Usage Examples
p("test %d ",1);
pl("test %d ",2); // first argument is an array
pl(F("test %d is in flash to save %s"),3,"memory"); // first argument is a __FlashStringHelper
Output:
test 1 test2
test 3
Could I have made this simpler? I have some ideas if I could figure out how to convert a __FlashStringHelper to a char[].