2

我正在尝试开发一个应用程序来通过串行端口与 pyserial 通信两台计算机。

基本思想是双向发送多个命令。

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

计算机 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()

计算机 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()

两种代码有时都能正常工作。有时执行会输出垃圾。我不知道是什么问题。使用 PySerial 从串行端口发送和写入我做错了什么?

在串口中读写是否更好实现一个线程程序用一个线程进行监听和读取,一个用于监听,另一个用于写?

4

2 回答 2

0

我认为您正在设置所有冲洗的比赛条件。例如,如果对方在您调用之前开始响应,则在读取之前刷新输入会杀死传入的数据read。你真的不需要所有这些围绕你的读写的刷新。

于 2012-10-05T17:23:32.633 回答
0

似乎您正在设置数据包冲突,这可能是您的输出中“垃圾”的来源。

您需要设置某种计时协议,或者通过在两台计算机上同步计数,或者通过建立突发通信,每台计算机踢出它的消息然后嗅探数据包。

于 2012-10-18T21:57:30.397 回答