Bartek Pacia
Bartek Pacia

Reputation: 1715

Bidirectional communication over USB between host PC and Raspberry Pi Pico

I'm trying to achieve bidirectional communication over my Raspberry Pi Pico's built-in micro-USB port. More specifically, I'm trying to make my computer send a ping to the Pico, and the Pico receives the ping and responds with a pong.

The code

This is the code that I run on my computer:

# This must not run on Pico, but on the host computer!

import serial
import time
import sys

# open a serial connection
s = serial.Serial("/dev/cu.usbmodem1101", 115200) # on my mac, this is how pico shows up

# blink the led
while True:
    s.write(b"ping\n")
    print("sent 'ping'")
    time.sleep(1)
    response = s.readline()
    print(f"received '{response}'")
    time.sleep(1)

And this is the code I put on my Pico (using the Thonny Python IDE):

import time
import sys

while True:
    # read a command from the host
    v = sys.stdin.readline().strip()
    print(f"received '{v}'")
    time.sleep(1)
    
    sys.stdout.write(b"pong\n")
    print("sent 'pong'")

I first click the green Run button in Thonny to put code on the Pico. Then, I run the first script on my computer with the following command:

$ python data_transfer_host.py

The problem

My Pico successfully receives the ping from the computer. But I don't know how to send the pong back to my computer. With the code I have now, the text pong is written to Thonny's console, like this:

screenshot of Thonny Python IDE showing a "pong" text visible in the console

I also tried using sys.stdout.print(b"pong\n") instead of sys.stdout.write but it results in an error: AttributeError: 'TextIOWrapper' object has no attribute 'print'.

Upvotes: 1

Views: 90

Answers (1)

BitLauncher
BitLauncher

Reputation: 693

What is the real intention - just having a bidrectional communication with the Raspberry Pi with text commands ending with \n?

If yes, then why not using the ethernet? Sending e. g. UDP/HTTP packets in both directions should work.

Or using RS232 the UART pins + some electronics and a USB-to-serial adapter from a 2nd USB port?

Thonny Python IDE communicates with the Raspberry Pi via USB too? Then what works and what does not - is probably defined by Thonny.

I normally access my Raspberry Pi via ethernet/SSH and start the python scripts directly in the shell console of the Ubuntu running on my Raspberry. There is even a command line debugger in python integrated - on Raspberry too?

If you don't use Thonny Python IDE the USB is unused and could be perhaps reconfigured with a proper library and simulate a serial interface for the connected PC (similar to FTDI's chip for RS232 = UART = serial interface).

Asking in the raspberry pi forum could bring also help.

Upvotes: -2

Related Questions