There are times (usually debugging) when I really hate having to type lines and lines of stuff like this:
Serial.print("a = ");
Serial.print(a, DEC);
Serial.print(", b = $");
Serial.println(b, HEX);
...and I just wish I had a proper printf() type of function for writing to the serial port.
Well printf and friends are actually in the AVR libc library so here's a 3-line hack to give a printf-like function, which would ideally be incorporated into Serial already as Serial.printf().
#include <stdio.h>
char _str[32]; // 32 chars max! increase if required to avoid overflow
#define writeln(...) sprintf(_str, VA_ARGS); Serial.println(_str)int a = 2, b = 3;
void setup() {
Serial.begin(9600);writeln("We're using writeln here\n");
writeln("a = %d, b = %d, a+b = %d", a, b, a+b);
}void loop() {
for (int i = 0; i < 256; i++) {
writeln("i = %3d ($%02x)", i, i);
delay(200);
}
}
I've found this useful so I'm presenting it here purely as a convenient hack...
Disadvantages are that it would be easy to overflow the _str[] buffer, but I've kept it small to save space (it's easy enough to make it bigger). Also that the vfprintf() library uses quite a lot of memory, but for smaller sketches there may be times when it's worth the trade-off.
Flames to /dev/null, as we used to say....
Docs for printf/sprintf/vfprintf are here: avr-libc: <stdio.h>: Standard IO facilities