2

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

user4157124
  • 2,809
  • 13
  • 27
  • 42
basil_man
  • 322
  • 5
  • 14

1 Answers1

1
  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.

user4157124
  • 2,809
  • 13
  • 27
  • 42
basil_man
  • 322
  • 5
  • 14
  • I have also seen `while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:` instead of using a `poll_obj`; but my test shows that it is slower. – basil_man Apr 29 '23 at 20:27
  • Note: the max write/read rate I got with this code is ~1000 Hz. I will be slower if the Pi Pico is doing work. – basil_man Apr 29 '23 at 20:51
  • My Pico somehow blocks on the ``sys.stdin.readline()`` – MaciejkaG Jun 28 '23 at 12:21
  • 1
    `sys.stdin.readline()` looks for `"\n"` to know when to return, so double check that "\n" is at the end of the string. You could also try terminating the string with"\r" or specifying the return symbol (`sys.stdin.readline('\n')`). – basil_man Jun 29 '23 at 14:59
  • Warning: On Windows "\n" is interpreted as "\r\n". (this applies to transferring bytes as well) – basil_man Aug 03 '23 at 01:05