Skip to content

Instantly share code, notes, and snippets.

@ctkjose
Last active September 3, 2019 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctkjose/09aaed811802ab083f0771a007ac9fcd to your computer and use it in GitHub Desktop.
Save ctkjose/09aaed811802ab083f0771a007ac9fcd to your computer and use it in GitHub Desktop.
A simple printf like interpolation for Arduino

serial_printi()

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 );
}

Use

serial_printi("Hello %s\n", "Jose");
serial_printi("Hello X=%d F=%f\n", 25, 340.36);

Notes

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment