Python – Reading binary data with PySerial from serial port

pyqtpythonqprocessqtserial-port

PyQT 4.7 does not have inherited class from QIODevice that allows to talk with serial port directly (e.g. QSerialDevice). So I thought that it would be easier for me to use QProcess class and implement the actual reading/writing to serial port from a different process that will interface with my main QT application using QProcess interface.

Now the problem is that amount of bytes sent and received is not the same when I am using the code below. So my question is how to correctly read binary data from a serial port and then forward everything to the stdout?

This is an excerpt from my main QT program that creates QProcess:

        self.micromouse_socket = QProcess()
        self.micromouse_socket.start("/home/ansis/Source/Perforce-pele/Pele/tools/console/comtalker.py", "")
        self.micromouse_socket.started.connect(self.on_micromouse_socket_started)
        self.label_8.setText("Starting COM...")

And this is the Process that will talk with Serial port (comtalker.py; non blocking part is not yet finished):

#!/usr/bin/python
import serial
import sys

if __name__ == "__main__":

    ser = serial.Serial(0)

    while 1 :
        x = ser.read(1)
        sys.stdout.write(x)
        sys.stdout.flush()

P.S. It could be that problem is somewhere else and not in PySerial. On the other computer I am writing to ttyS0 with this command "./binary_data_generator > /dev/ttyS0". The same code seemed to work fine when I was sending only ASCII characters (text+numbers)

Best Answer

It seems that PySerial (or a library that Pyserial depends on) is translating a single "0x0a" (\n) character into two characters "0x0d 0x0a"(\r\n). Both communication end-points are running on Linux, so I am not sure why someone would like to even translate those line endings at all...

Here strace indicates that sender sends only \n to ttyS0:

write(1, "M\n", 2)                      = 2
write(1, "\n", 1)                       = 1
write(1, "M\n", 2)                      = 2
write(1, "\n", 1)                       = 1

While debugging PySerial output I saw that each \n is prefixed with a \r.

Before claiming that this as a Bug I will do further investigation to find out who and why adds this carriage return...

Related Topic