# Serial echo example # Mirrors Arduino echo.ino and CircuitPython echo.py # # Run with Thonny (set interpreter to MicroPython (Raspberry Pi Pico)). # Type a line in the Thonny Shell and press Enter — the board reads the # line and sends it straight back, prefixed with "echo: ". # # Key concepts # ------------ # sys.stdin / sys.stdout — standard input/output streams, connected to the # USB serial port on the XIAO RP2040 # select.select() — checks whether a stream has data ready to read # WITHOUT blocking; essential for keeping the main # loop responsive while waiting for input # sys.stdin.readline() — reads bytes until '\n' and returns them as a str; # safe to call after select confirms data is waiting import sys import select print("XIAO RP2040 ready — type something and press Enter.") while True: # select.select(rlist, wlist, xlist, timeout) # rlist — streams to watch for readable data → [sys.stdin] # wlist — streams to watch for writable space → [] (unused) # xlist — streams to watch for errors → [] (unused) # timeout — seconds to wait; 0 = return immediately (non-blocking) # # Returns three lists matching the inputs. If readable is non-empty, # at least one byte is waiting in sys.stdin. readable, _, _ = select.select([sys.stdin], [], [], 0) if readable: # readline() reads up to and including the next '\n'. # Because select confirmed data is available, this will not block. line = sys.stdin.readline() # sys.stdout.write() sends text without appending an extra newline, # so the '\n' already inside 'line' terminates the echoed line. sys.stdout.write("echo: " + line)