Pi Pico: read/write data over usb cable
Question:
How can I read/write data to my Raspberry Pi Pico using Python/MicroPython over the USB connection?
(I have seen a lot of question across the internet on this with few answers, so I thought I share it here to make it easy to find)
Answers:
Directions:
- Use Thonney to put micropython code on to the Pi Pico. Save it as ‘main.py’.
- Unplug Pi Pico USB.
- Plug Pi Pico USB back in. (DON’T hold do the boot button)
- Run the PC Python code to send and receive data between the PC and Pi Pico.
Code for the Pi Pico:
read data from sys.stdin
write data using print
poll
is used 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("datar".encode())
mes = s.read_until().strip()
print(mes.decode())
if __name__ == "__main__":
main()
‘serial’ is PySerial
How can I read/write data to my Raspberry Pi Pico using Python/MicroPython over the USB connection?
(I have seen a lot of question across the internet on this with few answers, so I thought I share it here to make it easy to find)
Directions:
- Use Thonney to put micropython code on to the Pi Pico. Save it as ‘main.py’.
- Unplug Pi Pico USB.
- Plug Pi Pico USB back in. (DON’T hold do the boot button)
- Run the PC Python code to send and receive data between the PC and Pi Pico.
Code for the Pi Pico:
read data from sys.stdin
write data using print
poll
is used 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("datar".encode())
mes = s.read_until().strip()
print(mes.decode())
if __name__ == "__main__":
main()
‘serial’ is PySerial