micropython/micropython — pull request #901 by dpgeorge (2014-10-11 17:11:00+00:00)
Title: UART overhaul

This PR is intended to fully address issue #787, and also improve the UART class in general.

It allows for a UART receive buffer so you don't lose characters:

ua = pyb.UART(1, 9600, recv_buf_len=32)
... do stuff ...
buf = ua.recv(20) # will return up to 20 buffered chars

Default recv_buf_len is 64 bytes.

It allows for a Linux-like specification of VMIN and VTIME. For example, to read up to 20 chars, waiting at most 1000ms for the first, and then at most 5ms between chars, use:

buf = ua.recv(20, timeout=1000, timeout_chr=5)

Behaviour is: if no chars immediately available, wait for 1000ms. If no chars come by 1000ms then return empty bytes object (`b''`). If 1 char comes by 1000ms then read up to 20 chars. In this case returns a bytes object with 1-20 chars in it. The function will never take longer than 1000+19*5=1095ms to execute, and could take 0ms if 20 chars are waiting in the input buffer.

There is also recv_chr:

chr = ua.recv_chr(timeout=1000)

This returns 1 character, as an integer (not bytes object). It waits at most 1000ms for this char to arrive.

recv_into:

buf = bytearray(10)
n = ua.recv_into(buf, timeout_chr=5)

This will read up to 10 chars, waiting at most 5ms between them. It puts the chars in buf, and returns the number of chars filled in. The return value can be 0 (if no chars read, so function timed-out), or 1-10 if at least 1 char read.

Comments welcome! In particular, what do people think of the naming scheme for the methods and their keyword arguments?