使用Circuit Playground Express上的Circuit Python从主机接收数据

时间:2018-02-22 07:54:39

标签: adafruit micropython

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

我想读取从Circuit Playground Express通过USB连接的计算机传输的数据。使用input()工作正常,但我宁愿得到串口的缓冲区,这样循环就会继续,而没有输入。像serial.read()这样的东西。

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

4 个答案:

答案 0 :(得分:2)

This is now somewhat possible! In the January stable release of CircuitPython 3.1.2 the function serial_bytes_available was added to the supervisor module.

This allows you to poll the availability of serial bytes.

For example in the CircuitPython firmware (i.e. boot.py) a serial echo example would be:

import supervisor

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

and ensure when you create the serial device object on the host side you set the timeout wait to be very small (i.e. 0.01).

i.e in 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))

答案 1 :(得分:1)

显然,截至目前,这是不可能的。请参阅Adafruit here的完整讨论。

答案 2 :(得分:0)

艾登的答案引导我朝着正确的方向发展,我在这里找到了一个很好的(略有不同)如何使用Adafruit的supervisor.runtime.serial_bytes_available的示例(具体来说是89-95行):https://learn.adafruit.com/AT-Hand-Raiser/circuitpython-code

code.py的一个最小工作示例是输入,并以“ RX:string”格式设置新字符串的格式是

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 on 2019-08-02;带有samd21g18的Adafruit ItsyBitsy M0 Express。在macOS上通过mu-editor中的串行连接发送的消息。

样本输出

main.py output:
listening...
hello!
RX: hello!

答案 3 :(得分:0)

基于上述帖子,我有一个简单的示例可以工作,不确定它是否稳定或有用,但仍在此处发布:

CircuitPython代码:

import supervisor

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

PC代码

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']