3

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 ?

asked Dec 18, 2013 at 14:03
0

3 Answers 3

5

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);
answered Dec 18, 2013 at 14:09
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, unfortunately, I don't enough reputation to vote you, as am very new to stackoverflow. But, thanks very much :)
4

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.

answered Dec 18, 2013 at 14:07

Comments

1

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

answered Dec 18, 2013 at 14:10

2 Comments

Thank you very much, unfortunately, I don't enough reputation to vote you, as am very new to stackoverflow. But, thanks very much :)
@Sumanth Our intention is to give some idea about things. Voting is secondary.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.