I love old questions, and I like C (and I like printf for debugging).
There are two solutions (there are for sure more, I just mention this two):
Keep in mind the Arduino C (libraries) often does not support all escapes/formats (%f is missing)
First the "C-Style":
We just need a function, that writes a CHAR to Serial and associate this function with stdout (0)
#include <stdio.h>
char sputc(char c, FILE *) {
Serial.write(c);
return c;
}
void setup() {
fdevopen(&sputc, 0)¹; // tell stdout (0) what to use
Serial.begin(115200);
printf("Hello World! We are here %2.2d\n",42);
}
The other solution - my preferred one because it takes about 700 byte less, is the following:
I use vsnprintf¹ and varargs¹ to fill a buffer - that easy.
void say(char const* fmt, ...) {
va_list vars;
char buf[80]; // that is a drawback.
va_start(vars, fmt);
vsnprintf(buf, sizeof(buf), fmt, vars);
Serial.print(buf);
}
void setup() {
Serial.begin(115200);
say("we are here %2.2d\n",10);
}
¹this functions you find in internet.
mainin Arduino. You have thesetupfor initialization and theloopfor the continuing loopmainin Arduino, but it is hidden seeedstudio.com/wiki/Where_is_Main_Function