简体   繁体   English

与PySerial的双向串口通讯

[英]Bidirectional serial port communication with PySerial

I'm trying to develop an application to communicate two computer through the serial port with pyserial. 我正在尝试开发一个应用程序,以通过串行与pyserial通信两台计算机。

The basic idea is to send several commands in both directions. 基本思想是在两个方向上发送多个命令。

Computer A ---- INI ----> Computer B
Computer A <--- OKINI --- Computer B
Computer A ---- OK -----> Computer B

The code for the Computer A is: 计算机A的代码为:

s = serial.Serial(port='/dev/ttyUSB0', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
s.flushOutput()
s.write("*INI,COMPUTER_A*")
s.flushInput()  
data = s.read(18)
if data:
    print data
    s.flushOutput()
    s.write("*OK,COMPUTER_A*")
s.close()

The code for the Computer B is: 计算机B的代码是:

s = serial.Serial(port='/dev/ttyUSB0', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
s.flushInput()  
data = s.read(16)
if data:
    print data
    s.flushOutput()
    s.write("*OKINI,COMPUTER_B*")
    s.flushInput()
    data2 = s.read(15)
    if data2:
        print data2
s.close()

Both code works correctly sometimes. 两种代码有时都能正常工作。 There are times when an execution outputs garbagge. 有时执行程序会输出垃圾。 I don't know what is the problem. 我不知道是什么问题。 What am I doing wrong for send and write from a serial port with PySerial? 使用PySerial从串行端口发送和写入时,我在做什么错?

Is it better for read and write in the serial port implement a threaded program listening and reading with a threads, one for listen and another for write? 在串行端口中进行读取和写入是否更好地实现了一个线程程序的监听和线程读取,一个线程用于监听,另一个线程用于写入?

I think you're setting up race conditions with all your flushing. 我认为您正在通过所有冲洗设置比赛条件。 For example, flushing input just before a read would kill the incoming data if the other side started responding before you call read . 例如,如果在调用read之前另一端开始响应,则在read之前刷新输入将杀死传入的数据。 You really don't need all these flushes around your reads and writes. 您确实不需要在读取和写入过程中进行所有这些刷新操作。

it seems like you're setting up for packet collisions, which is probably the source of the 'garbage' in your outputs. 好像您要设置数据包冲突,这可能是输出中“垃圾”的来源。

you'll need to set up some sort of timing protocol, either by synchronizing a count on both computers, or by establishing burst communications, where each computer kicks out its messages then sniffs for packets. 您需要通过在两台计算机上同步计数或建立突发通信来建立某种定时协议,在这种通信中,每台计算机都会踢出其消息,然后嗅探数据包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM