PySerial - 全双工通信

8 投票
2 回答
12583 浏览
提问于 2025-04-17 13:26

使用PySerial实现全双工通信是否可能?具体来说,是否可以持续监控端口以接收输入,并在需要时进行写入?我想这应该可以通过线程来实现(而且串口接口不是全双工的吗?)。如果不行,那么在不传输数据时,监控串口的最佳方法是什么?是设置一个超时吗?

编辑:这是我尝试的代码。这个代码是针对TI的CC2540蓝牙低能耗芯片的。当我发送GATT初始化消息时,我期待收到一个回复(详细说明芯片的操作参数)……但我什么也没收到。

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 个回答

0

你没有设置超时时间,所以读取操作会一直等到接收到所有的数据字节,才会开始显示任何内容。

7

是的,串口硬件是全双工的,也就是说它可以同时发送和接收数据。你可以使用线程来同时进行接收(Rx)和发送(Tx)。另外,你也可以用一个线程循环来处理,这个循环会在读取数据时设置一个短暂的超时,然后在读取和写入之间交替进行。

撰写回答