Printing to the UART Console in MPLAB® X IDE Simulator

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

You can redirect the stdout stream when using MPLAB® XC8 C compiler so that printf() output is displayed in the simulator's Universal Asynchronous Receiver Transmitter (UART) console in MPLAB X IDE. To do this, you need to perform the following steps:

  1. Implement the putch() function
  2. Initialize the UART
  3. Enable the UART console in the IDE

The putch() Function

The printf() function formats the string it has been asked to print by expanding placeholders and modifiers. It then calls the function putch() to send each character of the formatted text to stdout. By customizing the putch() function, you can define the destination of stdout and have printf() "print" to any peripheral on your target device.

To use the UART console feature in the IDE, you must ensure that your putch() function sends its argument to the transmit register in the UART. The following code will work with most devices and you can copy this into your project. It will be called automatically by printf().

1
2
3
4
5
6
void putch(unsigned char data)
{
   while( ! PIR1bits.TXIF)          // wait until the transmitter is ready
       continue;
    TXREG = data;                     // send one character
}

Initializing the UART

Just like the UART on a real device, the simulated UART needs to be initialized. If you already have code in your project to initialize this peripheral, that same code should also work in the simulator. To use the UART console feature, the simulated UART does not need the same degree of configuration as the actual peripheral, so your code can be simplified if you like. The following code is sufficient for most devices:​

1
2
3
4
void init_uart(void) {
    TXSTAbits.TXEN = 1;               // enable transmitter
   RCSTAbits.SPEN = 1;               // enable serial port
}

Enable the UART Console

So that the IDE knows it should be redirecting UART transmissions to a console window, you need to enable this feature. To do this, open the Project Properties dialog for your project. Select the Simulator category, then, in the right-hand pane, select the Uart1 IO Options options category. Finally, enable the checkbox marked Enable Uart1 IO.

window to enable the UART in mplab x

Let's Print

To have the printf() output appear in the UART console, all you need to do is call your routine to initialize the UART, and then call printf(). The following test code does just that:​

1
2
3
4
5
6
void main(void) {
    init_uart();
    printf("Hello world\ntest value is %04d\n", 23);
   while(1)
       continue;
}

The UART 1 Output window will be automatically opened by the IDE once you run your program in the simulator.

UART 1 Output window