Serial connection problem with Pyserial after reboot

Viewed 851

I have a Python script to communicate with a measuring instrument over a RS232 serial port. Everything works fine, but every time I turn on the PC (Windows 10) the communication doesn't work in the beginning. I have to open a serial terminal (for example hterm) press the "connect" and "disconnect" button. After that the Python script works as expected, reading and writing to and from the instrument is no problem. Here is a short example of the code:

import serial, time
ser = serial.Serial(port='COM6', baudrate=19200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0, xonxoff=False, rtscts=False, dsrdtr=False)
time.sleep(1)
print(ser.isOpen()) #output: true
ser.write(b'READ:CH1\r\n')
time.sleep(1)
print("read:" + ser.read(18).decode('utf-8'))
ser.close()
print(ser.isOpen()) #output: false

The instrument doesn't receive the data "READ:CH1" or any other command. Because of this there isn't any transmitted data to the PC via ser.read(). I tried every possibility with hardware handshakes and very long sleep times. I guess there's a problem between Windows and Pyserial. In Python the port is open, but Windows doesn't send the data. Do you have any ideas what I could do? Thanks for your help.

Best regards

Edit with solution:

Instead of or additional to "Serial.flushInput()" and "Serial.flushOutput()" you need "Serial.reset_input_buffer()" and "Serial.reset_output_buffer()".

2 Answers

If you are using a third-party tool and then the script works fine, then I think there is some garbage data present in the buffers of either side, flushing the serial port on the hardware device and on the python script too might work and verify the data being received on the hardware device it is possible garbage is being appended on the commands, also try to use some header bits which keep errors at bay in this kind of communication.

Use some serial port sniffer to verify what is being sent, like this

Look at https://github.com/pyserial/pyserial/issues/329

https://github.com/pyserial/pyserial/issues/329#issuecomment-400852426

https://github.com/pyserial/pyserial/issues/329#issuecomment-503059537

Do you see this?

Another issue that might be related:

https://github.com/pyserial/pyserial/issues/485

Another thing you could try is to open and close the port first.

That's the same thing you are doing with hterm for

ser = serial.Serial()
time.sleep(1)
print(ser.isOpen()) #output: true
ser.close()

ser = serial.Serial()
time.sleep(1)
print(ser.isOpen()) #output: true
...

Does this work?

Related