How to use the primary UART
MicroPython provides access to the primary UART via sys.stdin (see sys.stdin limitations) and sys.stdout (and sys.stderr as an alias to sys.stdout). Unlike Python3, MicroPython does not allow overriding stdin, stdout and stderr with other stream objects.
sys.stdin sys.stdin supports standard stream methods read and readline in text mode, converting carriage return (\r) to newline (\n).
Note Do not use the stdin methods readlines or readinto because they will be removed in future firmware.
Use sys.stdin.buffer (instead of sys.stdin) for binary mode without any line ending conversions. The read() method takes a single, optional parameter of the number of bytes to read. For a positive value, read() blocks until receiving that many bytes from the standard stream methods primary UART. For non-blocking, call read() without the parameter (or with a negative value) and it returns whatever characters are available or None if no bytes are waiting.
sys.stdout supports the write() method in text mode, sending an additional carriage return (\r) before each newline (\n). Use sys.stdout.buffer (instead of sys.stdout) for binary mode without any line ending conversions. The write() method buffers its output, and can return before sending all bytes out on the UART.
sys.stdin limitations
Note that sys.stdin provides access to a filtered input stream with the following limitations:
- Only works as long as ATAP = 4.
- You can only configure the primary serial port via AT commands (for example ATBD to set the baud rate) and not from MicroPython.
- Receiving a Ctrl-C character generates a KeyboardInterrupt.
- You can change the interrupt character using micropython.kbd_intr(ch) where ch is the new character to use (3 corresponds to Ctrl-C) or -1 to disable the keyboard interrupt entirely.
- MicroPython always resets the keyboard interrupt to Ctrl-C at the start of each REPL line, before executing code entered via paste mode, and when executing compiled code at startup or via Ctrl-R.
- The escape sequence (configured with ATCC, +++ by default) protected by a guard time (configured with ATGT, 1 second by default) of no data before and after the escape sequence will always enter Command mode.
- Escape sequence handling can cause delays when reading from sys.stdin.
- You can send ATPY^ in Command mode to force a KeyboardInterrupt, even if it was disabled via micropython.kbd_intr(-1).
PDF
