Redirect stdout for Use With printf() in the MPLAB® XC32 Compiler

Last modified by Microchip on 2023/11/09 09:12

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.​
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <p32xxxx.h>
#include
<stdio.h>

void _mon_putc(char c);
void myOutputFunction(char c);

int main (void)
{
    setbuf(stdout, NULL);
    printf("Hello World!");

   while(1);  
}

void _mon_putc(char c)
{
    myOutputFunction(c); // printf() passes each character to write to _mon_putc(), which in turn passes each character to a custom output 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.