I have a python program that reads data from a USB serial port connected to a computer. The computer sends data packets from a simulation program (I didn't write this).

The data is made of strings of no more than 200 bytes serially with 21 data fields separated by commas at a baud rate of 115200 with 8N1.

In the python program, I have:

ser = serial.Serial(port=PORTNAME, baudrate=115200, timeout=.02)
while True:
    data = ser.read(200)

Most of the time, the data will be exactly 21 fields, but sometimes the data variable will be a string that has one entire data packet as well as the beginning of the next one appended to it, and the function that parses each individual data field will obviously return an exception.

Something I tried just for fun is adding a lot of print statements in the loop, which made the exception in the program happen significantly faster. I think it might have to do with the time.

Does anyone know how I can fix this? If not, I can just hard code a hack in the function that parses the data.


It looks like you have gone with a default of no flow control, and you have also specified no parity bits.

Do you have control over the communications parameters on both sides? I know you said you didn't write the PC side but do you have the ability to specify port settings such as baud rate, parity bit, flow control?

If so, I would try turning on hardware flow control and perhaps even or odd parity even though it is not going to provide much protection.

See the third example here.

It's the "parity=serial.PARITY_EVEN, rtscts=1" part that I am suggesting, but of course you have to be able to make the same change on both sides.

p.s. In my opinion, you should still be doing what I think you're calling a hack ;-) which is to look at the data received and make sure it adheres to the expected format.

  • Unfortunately, the simulation is just a representation of something that's going to happen in real life, where I would not be able to change the settings on the computer. Thanks for the reply.
    – Vasting
    Jun 18 '17 at 23:12
  • 1
    You might still try turning on rtscts=1. It's possible the PC side is already using it. If you turn it on and the PC side is not using it, all that's going to happen is if your side attempts to flow control the session the other side will ignore it and data loss could occur, similar to what your seeing now occasionally. If it doesn't help, put your code back the old way. Jun 20 '17 at 2:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.