Reputation: 316
I'm trying to send 9 bytes through a serial port (tested with RS232, RS485) with Python 2.7 pySerial package. If I write out the bytes to the serial port, some of the bytes randomly get lost (do not arrive on the receiving end). If I use a 1 millisec wait between every write of a single byte, all bytes arrive to the receiving end.
I tested the functionality between 2 serial terminals on the same OS.
Here is the code fragment which causes packet (byte) losses:
import serial
import struct
ser = serial.Serial()
ser.baudrate = 9600
ser.parity = "N"
ser.rtscts = False
ser.xonxoff = False
ser.write(struct.pack('B', 0x61))
ser.write(struct.pack('B', 0x62))
ser.write(struct.pack('B', 0x63))
...
ser.close()
The fragment which is working:
import serial
import struct
from time import sleep
ser = serial.Serial()
ser.baudrate = 9600
ser.parity = "N"
ser.rtscts = False
ser.xonxoff = False
ser.write(struct.pack('B', 0x61))
sleep(0.001)
ser.write(struct.pack('B', 0x62))
sleep(0.001)
ser.write(struct.pack('B', 0x63))
sleep(0.001)
...
ser.close()
What can be the root cause for the random packet losses?
System details:
Test environment:
Upvotes: 0
Views: 3217
Reputation: 2653
Typically USB serial converters have to be configured to not flush the buffers on close. As you're seeing if you provide a sleep to wait for the data to complete it works. But if you just dump a bunch of characters then close the device it's buffer may still have data which gets trashed on the close. I'd simply recommend either configuring your device to not flush the buffers (if possible) or wait the character time before performing your close.
Upvotes: 1