PySerial - 全双工通信

8
可以使用PySerial实现全双工通信吗?具体而言,是否可以在需要时持续监控端口并进行写操作?我想可以使用线程实现(串行接口是全双工的,不是吗?)。如果不行,那么在不传输数据时监控串口的最佳方法是什么?使用超时吗?
编辑:以下是我的尝试。此代码针对TI的CC2540蓝牙LE芯片。发送GATT init消息后,我期望会收到回复(详细介绍芯片的操作参数)... 但我什么都没有得到。
import serial
import threading
from time import sleep

serial_port = serial.Serial()

GAP_DeviceInit  = \
                "\x01\x00\xfe\x26\x08\x03\x00\x00\x00\x00\x00\x00\x00\x00\
                \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\
                \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00"

def read():
    while True:
        data = serial_port.read(9999);
        if len(data) > 0:
            print 'Got:', data

        sleep(0.5)
        print 'not blocked'

def main():
    serial_port.baudrate = 57600
    serial_port.port = '/dev/ttyACM0'
    serial_port.timeout = 0
    if serial_port.isOpen(): serial_port.close()
    serial_port.open()
    t1 = threading.Thread(target=read, args=())
    while True:
        try:
            command = raw_input('Enter a command to send to the Keyfob: \n\t')
            if (command == "1"):
                serial_port.write(message)
        except KeyboardInterrupt:
            break
    serial_port.close()
2个回答

7

是的,串口硬件是全双工的。您可以使用线程同时进行接收和发送。或者,您可以使用单个线程循环,使用短超时进行读取,并在读取和写入之间交替执行。


1
你能给一个简短的例子吗?或者指出代码示例中的任何问题。第二种方法的问题在于我不知道何时需要发送数据...用户可以随时选择要发送的消息。 - stephenfin

0

你没有指定超时时间,因此读取将等待接收到全部字节数后才显示任何内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接