简体   繁体   中英

Bidirectional serial port communication with PySerial

I'm trying to develop an application to communicate two computer through the serial port with 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:

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:

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?

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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