ESP32 printf()
tl;dr – For the ESP32 microcontrollers, ALWAYS terminate a printf() function call with a newline character.
Consider the humble printf(“Hello world!\n”) statement. This elementary function call is the poor man’s tool of choice where a suitable JTAG debugger is either not available or simply a hassle to use. Let us examine a code snippet.
int foo = 0; printf("Hello bar!\n"); foo++; printf("The value of foo is now: %d", foo);
All of my wat. It turns out that the second printf() call does… nothing? Is foo even incremented? Fear not, for foo does actually increment itself, and the second printf() places characters in the stream buffer but doesn’t update the terminal.
int foo = 0; printf("Hello bar!\n"); printf("Updating foo!"); foo++; if(foo == 1) { printf("Foo has been increased.\n"); } else { printf("Nothing to see here!"); }
Clearly, the branch where foo == 1 was entered, so printf() is not a blocking function if it doesn’t process a newline “\n” character. That formatting looks ugly. Let’s fix it.
int foo = 0; printf("Hello bar!\n"); printf("Updating foo!"); foo++; if(foo == 1) { printf("\nFoo has been increased."); } else { printf("Nothing to see here!"); }
I, simply, cannot win. The buffer is flushed only WHEN a newline character is encountered and NOT at the end of a call in which it was encountered.
A suboptimal solution is to use setvbuf(stdout, NULL, _IONBF, 0); which will work, but it is inefficient. Just remember to use a newline.