Newlib printf delay

1k views Asked by At

I am having a strange problem with newlib's printf function, which is re-directed to uart port.

The problem can be well explained with an example.

printf(" hi ");
... 
...//some other simple code. like a++; 
...
printf(" hello ");

Now when I run the program, 'hi' doesn't appear until then next printf is reached/called. i.e., when 'hello' is supposed to be printed, it prints 'hi', .. this delay of 1 call is carried always. and the last printf doesn't get printed at all.

Where is my UART code :

int write(int file, char *ptr, int len) {
unsigned int i;
int de =1;
//initialize_Uart(de);// NOT REQUIRED as UBOOT has already done the job.

    /* Transmitting a char from UART */
    for (i = 0; i < len; ++i, ++ptr)
    {
        while (!(IN_8(DUART1_ULSR1)&(0x20))); // wait for the CTS bit is cleared
                OUT_8(DUART1_UTHR, *ptr);

    }
return len;
}

What is the solution for this ?

3

There are 3 answers

0
Some programmer dude On BEST ANSWER

You have to remember that output to streams (like stdout) is by default buffered.

Nothing is written until the buffer is flushed, either explicitly by calling fflush(stdout) or semi-explicitly by adding a newline in the the text you print (e.g printf(" hi \n");), or implicitly by writing enough so that the buffer fills up and is flushed by the library.

1
Devolus On

The standard output is usually buffered. Normally when a new line character is encountered the buffer is flushed, or when it becomes full, at which point you may see only partial data.

You can force the flushing yourself by either doing

printf("\n");  <- Note the newline which should be present in your output.

using

fflush(stdout);

Or you can change the buffer size by setting the buffer to NULL, which will cause the standard output to be written immidiatly.

setbuf(stdout, NULL);
2
Chinna On

Use fflush(stdout); Generally buffering is there in standard input and output. You can flush the buffer using fflush()