I ran into a situation where it would be desirable to have a non-blocking getchar(). Basically, where I want to spit out data over the UART to a serial console, and keep doing so until the user presses a key. Obviously, when getchar() is blocking, it will stall the loop when checking if a key has been pressed.
I was wondering about how I could go about implementing, in the context of using the avr-libc standard library's stdio (stdin, stdout, fdev_setup_stream(), etc.), a non-blocking read of the standard input stream.
At the moment, I just have the usual blocking get() implementation to read a character from UART (AVR part I'm using has combined LIN/UART functionality, so registers are named LIN*):
int uart_getchar(FILE *stream) {
loop_until_bit_is_set(LINSIR, LRXOK);
return LINDAT;
}
A strategy I had in mind was to take advantage of fdev_set_udata(). I would use the udata value as a flag indicating whether I want blocking or non-blocking functionality. Then, in my UART get() implementation, I would simply switch functionality depending on the value of the flag. Something like this, perhaps:
int uart_getchar(FILE *stream) {
if(*((uint8_t *)fdev_get_udata(stream)) & FLAG_NON_BLOCK) {
return (bit_is_set(LINSIR, LRXOK) ? LINDAT : EOF);
} else {
loop_until_bit_is_set(LINSIR, LRXOK);
return LINDAT;
}
}
Will this work? Has anyone done anything like this before?