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:

  1. 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.
  2. 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.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.