Tag: _write

Lesson 007: Redirecting printf to UART Part 3

After speaking with the support staff at Renesas, I was finally able to find out how to properly redirect STDOUT and STDIN. Instead of overriding _printf, we will instead overwrite _write and _read.

Let’s get started!

First thing to note is that the Synergy Configuration screen is a little bit different, and it’s better IMHO!

We go though the standard project generation, making sure to add the UART driver and configure it the same as we have been.

We can delete #include <stdarg.h> from the top of our source file (since we no longer need to use a custom printf).

Delete the function prototype and implementation to _printf and replace it with the following _write implementation:

int _write(int file, char *buffer, int count);
int _write(int file, char *buffer, int count)
{
    // As far as I know, there isn't a way to retrieve how many
    // bytes were send on using the uart->write function if it does not return
    // SSP_SUCCESS (unless we want to use the tx interrupt function and a global counter
    // so, we will send each character one by one instead.
    int bytesTransmitted = 0;

    for (int i = 0; i < count; i++)
    {
        // Start Transmission
        transmitComplete = false;
        ssp_err_t err = g_uart.p_api->write(g_uart.p_ctrl, (uint8_t const *)(buffer + i), 1);
        if (err != SSP_SUCCESS)
        {
            break;
        }
        while (!transmitComplete)
        {
        }

        bytesTransmitted++;
    }

    return bytesTransmitted;
}

Next, we replace all of our _printf function calls with the standard printf.

The final item on the agenda is to disable output buffering. Normally, printf and scanf will only run when a new line character is received in the input/output stream.

Since we want serial output to show up immediately, we need to disable this buffering.

Somewhere before our first printf call, add the lines

 // Disable Output Buffering
 setvbuf(stdout, NULL, _IONBF, OUTPUT_BUFFER_SIZE);

As always, full source code is on the companion GitHub site https://github.com/lycannon/ajwrs/tree/master/Lesson007