Where does printf get directed to by default?

29 Nov 2010

Wher does printf() get directed to by default?  Like for instance in this program....

 

// example writing to SD card, sford

#include "mbed.h"
#include "SDFileSystem.h"

SDFileSystem sd(p5, p6, p7, p8, "sd"); // the pinout on the mbed Cool Components workshop board
 
int main() {
     printf("Hello World!\n");   
     mkdir("/sd/mydir", 0777);
    
    FILE *fp = fopen("/sd/mydir/sdtest.txt", "w");
    if(fp == NULL) {
        error("Could not open file for write\n");
    }
    fprintf(fp, "Hello fun SD Card World!");
    fclose(fp); 

    printf("Goodbye World!\n");
}
29 Nov 2010

OK, I see that printf() get directed to the serial port.  So my next question is: how is this different than pc.printf()?  Is it that printf() is at a fixed baud rate of 9600 8N1 and pc.printf() can be customized?

29 Nov 2010

Hi Freddie,

Yep, that's right. The printf() goes to "stdout", which is the mbed USB serial port (UART0 on the LPC1768, which is read by the mbed interface and converted to USB).

Using printf called on an object means it can easily be replaced by other objects. For example, if you had:

Serial output(USBTX, USBRX);
:
output.printf("Hello ");
output.printf("World!\n");

you could easily change it to put puting on an LCD without changing any of the code using it:

TextLCD output(...pins...);   // just chance what object "output" is
:
output.printf("Hello ");
output.printf("World!\n");

As you say, having the object gives you control over the aspects of the object, so in the case of a Serial port, that is things like baud rate. So printf() is great for debugging, whilst object.printf() is more useful/used when it is explicitly part of your application.

Simon

04 Feb 2012

Hi,

So with the LPC11U24, since it only has one UART does a printf() go both to pins p9, and out USBTX ?

Thanks, Serge

29 Feb 2016

Just thought this might be helpful for others...

The default printf() can be reconfigured as follows:

Setup the pc serial port with:

Serial pc(USBTX, USBRX);

Then inside your initialization function you can set the baud rate (away from the default):

pc.baud(115200);

Then either pc.printf() or just printf() can be used over the debug USB VCP at a different baud rate or configuration.