Scientific progress goes "Boink"?

Xilinx SDK: Stop getchar() from waiting for RETURN

I often want to read a single character from the UART or stdin. By default getchar() buffers all input until a RETURN character occurs.

Here are two ways to handle this:

  • You can turn off the buffering on the stdin stream:
    setvbuf(stdin, NULL, _IONBF, 0);
    int c = getchar();
    
  • Or you just don’t use getchar() at all. Use inbyte() instead (this is what getchar() does anyway):
    #include "xuartps_hw.h"
    
    char c = inbyte();
    
  • You can use XUartPs_IsReceiveData() to check if a character is available before you call inbyte() :
    #include "xuartps_hw.h"
    
    if (XUartPs_IsReceiveData(STDIN_BASEADDRESS)) {
        char c = inbyte();
    }
    

Leave a comment