开发者

Reading binary data with PySerial from serial port

开发者 https://www.devze.com 2023-02-24 00:33 出处:网络
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 implemen

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 th开发者_运维问答at 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)


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


I think the stdout is not in binary mode by default. That's hy the non-ascii bytes seems to be lost. See this question, it may help.

If I am understanding correctly, you want to use the std i/o as communication pipe between two processes. I would recommend to use one of the multiprocess module for that

I hope it helps

0

精彩评论

暂无评论...
验证码 换一张
取 消