如何使用Raspberry Pi Pico从电脑读取数据?

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

如何使用 MicroPython 和 pyserial 将数据从计算机读取到 Raspberry Pi Pico?

pyserial micropython raspberry-pi-pico
1个回答
0
投票

我也遇到了这个问题,从这个link我能够解决这个问题。要从 USB 端口读取数据,请使用“sys.stdin.buffer.read(8)”。

这是一个简短的代码,您可以将其上传到 pico 来执行此操作。

import time
import sys

while True:
      print("hello")
      data = sys.stdin.buffer.read(8)
      # to convert to string use data = sys.stdin.buffer.read(8).decode("utf-8")
      print(data)

      time.sleep(1)

使用此代码,它将等待直到 8 个字节进入,在此之前它将空闲。我确信有办法解决这个问题,只是还没有尝试过。

我使用Arduino IDE串行监视器发送数据。在 Thonny 中上传此代码(将其另存为 main.py,以便在通电时启动),然后断开 pico,重新插入,然后打开 Arduino 串行监视器。发送类似“12345678”的内容,它应该将其吐出。

编辑:

上面的代码将处于空闲状态,直到您向其发送数据。要在没有发送数据的情况下让 pico 继续运行,请使用以下命令():

import time
import sys
import select

while True:
   print("hello")
   res = select.select([sys.stdin], [], [], 0)
   data = ""
   while res[0]:
      data = data + sys.stdin.read(1)
      res = select.select([sys.stdin], [], [], 0)
   print(data, end = "")
   time.sleep(1)

并且您可以直接使用 Thonny 发送数据,不需要 Arduino IDE。

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