This simple function does an interpolation on a formatted string similar to printf()
.
Its meant to be flexible and small.
void serial_printi(const char *format, ...){
char ch;
bool flgInterpolate = false;
va_list args;
va_start( args, format );
for( ; *format ; ++format ){
ch = *format;
if(flgInterpolate){
flgInterpolate = false;
if((ch=='d') || (ch=='c')){
Serial.print(va_arg(args, int));
}else if(ch=='s'){
Serial.print(va_arg(args, char*));
}else if(ch=='o'){
Serial.print(va_arg(args, unsigned int));
}else if((ch=='f') || (ch=='e') || (ch=='a') || (ch=='g')){
Serial.print(va_arg(args, double));
}else{
Serial.print('%');
Serial.print(ch);
}
}else if(ch=='%'){
flgInterpolate = true;
}else{
Serial.print(ch);
}
}
va_end( args );
}
serial_printi("Hello %s\n", "Jose");
serial_printi("Hello X=%d F=%f\n", 25, 340.36);
Use "%d", "%c" for int
, char
, long
, short
, and other values that can be casted to int
.
Use "%s" for char *
.
Use "%f" for double
or float
or similar values that can be casted to double
.
This function does NO type checking.