Thursday, May 26, 2022

[SOLVED] How can i get raspberry pi pico to communicate with PC / external devices

Issue

For example when i give 5 to the code, i want to turn on the led in our rpi pico (rpi pico connected to pc with cable)

#This code will run in my computer (test.py)

x=int(input("Number?"))
if (x==5):
    #turn on raspberry pi pico led

The code of rpi pico:

#This code will run in my rpi pico (pico.py)

from machine import Pin
led = Pin(25, Pin.OUT)

led.value(1)

or vice versa (doing something in the code on the computer with the code in the rpi pico)

and how can i call/get a variable in pc to rpi pico

note: I am writing a code with opencv python and I want to process the data from my computer's camera on my computer and I want rpi pico to react according to the processed data. And raspberry pi pico connected to pc with cable.


Solution

A simple method of communicating between the host and the Pico is to use the serial port. I have a rp2040-zero, which presents itself to the host as /dev/ttyACM0. If I use code like this on the rp2040:

import sys
import machine

led = machine.Pin(24, machine.Pin.OUT)

def led_on():
    led(1)

def led_off():
    led(0)


while True:
    # read a command from the host
    v = sys.stdin.readline().strip()

    # perform the requested action
    if v.lower() == "on":
        led_on()
    elif v.lower() == "off":
        led_off()

Then I can run this on the host to blink the LED:

import serial
import time

# open a serial connection
s = serial.Serial("/dev/ttyACM0", 115200)

# blink the led
while True:
    s.write(b"on\n")
    time.sleep(1)
    s.write(b"off\n")
    time.sleep(1)

This is obviously just one-way communication, but you could of course implement a mechanism for passing information back to the host.



Answered By - larsks
Answer Checked By - Katrina (WPSolving Volunteer)