Newlib printf 延迟

Sum*_*nth 3 c newlib uart

我在使用 newlib 的 printf 函数时遇到一个奇怪的问题,该函数被重定向到 uart 端口。

这个问题可以通过一个例子很好的解释。

printf(" hi ");
... 
...//some other simple code. like a++; 
...
printf(" hello ");
Run Code Online (Sandbox Code Playgroud)

现在,当我运行该程序时,直到到达/调用下一个 printf 之前,“hi”才会出现。即,当应该打印“hello”时,它会打印“hi”,.. 始终会执行 1 个调用的延迟。最后一个 printf 根本没有被打印。

我的 UART 代码在哪里:

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;
}
Run Code Online (Sandbox Code Playgroud)

有什么解决办法吗?

Dev*_*lus 5

标准输出通常是缓冲的。通常,当遇到新行字符时,缓冲区会被刷新,或者当缓冲区已满时,此时您可能只能看到部分数据。

您可以通过以下任一方式强制自己冲洗

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

使用

fflush(stdout);
Run Code Online (Sandbox Code Playgroud)

或者您可以通过将缓冲区设置为 来更改缓冲区大小NULL,这将导致立即写入标准输出。

setbuf(stdout, NULL);
Run Code Online (Sandbox Code Playgroud)