Redirect stdout for Use With printf()
By default, the MPLAB® XC32 compiler's libraries use UART2 for STDOUT. This means that formatted output functions such as printf() will send their output to UART2 (as opposed to the terminal on a PC). In some cases, you may want to use some other peripheral or mechanism for your output. To accomplish this, there are two steps that must be taken:
- You must do one of the following:
- Disable buffered outputs to stdio with setbuf(stdout, NULL) in your initialization code.
- Call fflush(stdout) after each call to printf().
- Insert a "\r\n" at the end of every string you wish to print.
- Write a custom replacement for _mon_putc() to write one character to the output of your choice. The code below shows part of an example of how to redirect stdout from UART2 to anything you want by using your own custom function.
The _mon_putc()function is defined in the PIC32 libraries with the weak attribute tag. This means that if another function with the same name is found in a project without the weak attribute, that one will take precedence and the weak one will be ignored.