You can redirect the stdout stream when using MPLAB® XC8 C compiler so that printf() output is displayed in the simulator's UART console in MPLAB X IDE. To do this you need to perform the following steps:
- Implement the putch() function
- Initialize the UART
- 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 customising 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().
Initialising 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:
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.
To have the printf() output appear in the UART console, all you need to do is call your routine to initialize the UART, then call printf(). The following test code does just that:
The UART 1 Output window will be automatically opened by the IDE once you run your program in the simulator.