如何让 Raspberry Pi pico 与 PC/外部设备通信?

问题描述 投票:0回答:1

例如,当我给代码输入 5 时,我想打开 RPi pico 中的 LED(通过电缆连接到 PC)。

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

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

RPi pico 的代码:

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

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

led.value(1)

反之亦然(使用 RPi pico 中的代码在计算机上的代码中执行某些操作)。

如何将 PC 中的变量调用/获取到 RPi pico?

注意:我正在使用 OpenCV Python 编写代码,我想在我的计算机上处理来自计算机摄像头的数据。我希望 RPi pico 根据处理后的数据做出反应。

python raspberry-pi micropython raspberry-pi-pico
1个回答
9
投票

主机和Pico之间通信的一种简单方法是使用串行端口。我有一个 rp2040-zero,它向主机呈现为

/dev/ttyACM0
。如果我在 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()

然后我可以在主机上运行此命令以使 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)

这显然只是单向通信,但您当然可以实现一种将信息传递回主机的机制。

© www.soinside.com 2019 - 2024. All rights reserved.