3

我正在使用 Adafruit 的 Circuit Playground Express,并且正在使用 Circuit Python 对其进行编程。

我想读取通过 USB 连接 Circuit Playground Express 的计算机传输的数据。使用input()工作正常,但我宁愿获得串行缓冲区,以便在没有输入的情况下继续循环。类似的东西serial.read()

import serial不适用于 Circuit Python,或者我必须安装一些东西。我还能做些什么来使用 Circuit Python 读取串行缓冲区?

4

3 回答 3

4

这现在有点可能!在CircuitPython 3.1.2 的 1 月稳定版本中,该功能serial_bytes_available被添加到supervisor模块中。

这允许您轮询串行字节的可用性。

例如,在 CircuitPython 固件(即boot.py)中,串行回显示例将是:

import supervisor

def serial_read():
   if supervisor.runtime.serial_bytes_available():
       value = input()
       print(value)

并确保在主机端创建串行设备对象时将超时等待设置为非常小(即 0.01)。

即在python中:

import serial

ser = serial.Serial(
             '/dev/ttyACM0',
             baudrate=115200,
             timeout=0.01)

ser.write(b'HELLO from CircuitPython\n')
x = ser.readlines()
print("received: {}".format(x))
于 2019-04-17T02:04:55.240 回答
4

我根据上面的帖子得到了一个简单的例子,不确定它有多稳定或有用,但仍然在这里发布:

电路Python代码:

import supervisor

while True:
    if supervisor.runtime.serial_bytes_available:
        value = input().strip()
        print(f"Received: {value}\r") 

个人电脑代码

import time
import serial
ser = serial.Serial('COM6', 115200)  # open serial port

command = b'hello\n\r'
print(f"Sending Command: [{command}]")
ser.write(command)     # write a string

ended = False
reply = b''

for _ in range(len(command)):
    a = ser.read() # Read the loopback chars and ignore

while True:
    a = ser.read()

    if a== b'\r':
        break

    else:
        reply += a

    time.sleep(0.01)

print(f"Reply was: [{reply}]")

ser.close()
c:\circuitpythontest>python TEST1.PY
Sending Command: [b'hello\n\r']
Reply was: [b'Received: hello']
于 2020-05-11T21:07:39.133 回答
3

艾登的回答让我朝着正确的方向前进,我在这里找到了一个很好的(并且略有不同)的例子,说明如何supervisor.runtime.serial_bytes_available从 Adafruit 中使用(特别是第 89-95 行):https ://learn.adafruit.com/AT-Hand-Raiser/电路python代码

一个最小的工作示例code.py接受输入并以“RX:字符串”的形式格式化一个新字符串是

import supervisor

print("listening...")

while True:
    if supervisor.runtime.serial_bytes_available:
        value = input().strip()
        # Sometimes Windows sends an extra (or missing) newline - ignore them
        if value == "":
            continue
        print("RX: {}".format(value))

测试于:Adafruit CircuitPython 4.1.0 于 2019-08-02;带有 samd21g18 的 Adafruit ItsyBitsy M0 Express。在 macOS 上的 mu-editor 中使用串行连接发送的消息。

样本输出

main.py output:
listening...
hello!
RX: hello!
于 2019-10-10T06:57:31.770 回答