Search code examples
pythonmicropythonraspberry-pi-pico

Read/write data over Raspberry Pi Pico USB cable


How can I read/write data to Raspberry Pi Pico using Python/MicroPython over the USB connection?


Solution

    1. Use Thonny to put MicroPython code on Raspberry Pi Pico. Save it as 'main.py'.
    2. Unplug Raspberry Pi Pico USB.
    3. Plug Raspberry Pi Pico USB back in. (don't hold do the boot button).
    4. Run the PC Python code to send and receive data between PC and Raspberry Pi Pico.

    Code for Raspberry Pi Pico:

    • Read data from sys.stdin.
    • Write data using print.
    • poll to check if data is in the buffer.
    import select
    import sys
    import time
    
    # Set up the poll object
    poll_obj = select.poll()
    poll_obj.register(sys.stdin, select.POLLIN)
    
    # Loop indefinitely
    while True:
        # Wait for input on stdin
        poll_results = poll_obj.poll(1) # the '1' is how long it will wait for message before looping again (in microseconds)
        if poll_results:
            # Read the data from stdin (read data coming from PC)
            data = sys.stdin.readline().strip()
            # Write the data to the input file
            sys.stdout.write("received data: " + data + "\r")
        else:
            # do something if no message received (like feed a watchdog timer)
            continue
    

    Code for PC:

    import serial
    
    
    def main():
        s = serial.Serial(port="COM3", parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, timeout=1)
        s.flush()
    
        s.write("data\r".encode())
        mes = s.read_until().strip()
        print(mes.decode())
    
    
    if __name__ == "__main__":
        main()
    

    serial is PySerial.