简体   繁体   English

PyQT5 使用 QtSerialPort 从端口读取问题

[英]PyQT5 problem with reading from port with QtSerialPort

I am currently trying to communicate with a device which sends a data stream by COM. I am having a weird problem with QtSerialPort which I currently don't know how to solve.我目前正在尝试与通过 COM 发送数据 stream 的设备进行通信。我在使用 QtSerialPort 时遇到了一个奇怪的问题,我目前不知道如何解决。 The description of the problem is: When I restart the device and restart my application, in the application I can open the corresponding port without any error.问题描述是:当我重启设备并重启我的应用程序时,在应用程序中我可以打开相应的端口,没有任何错误。 However, I do not receive any data from the device.但是,我没有从设备收到任何数据。 I am trying to read data from the COM-Port with the signal readyRead .我正在尝试使用信号readyRead从 COM 端口读取数据。 Now, when I open the port with another program B which uses python's serial, I can successfully read from the device after a restart.现在,当我用另一个使用 python 串口的程序 B 打开端口时,我可以在重启后成功地从设备读取。 Now, after reading successfully from the device with program B, I can also successfully read from the device using the QT-Program A, but only if I do not restart the device.现在,在使用程序 B 从设备成功读取后,我也可以使用 QT 程序 A 从设备成功读取,但前提是我不重启设备。 The following code contains the isolated port with QtSerial which reproduces the above mentioned problem.以下代码包含带有 QtSerial 的隔离端口,它重现了上述问题。

import sys
from PyQt5 import QtSerialPort
from PyQt5.QtCore import *
from PyQt5.QtSerialPort import *
from PyQt5.QtWidgets import QApplication, QMainWindow

class QtSerialTest(QMainWindow):
    def __init__(self, parent=None) -> None:
        super().__init__()

        self.port_com_port = QtSerialPort.QSerialPort()
        self.port_com_port.setPortName("COM4")
        self.port_com_port.setBaudRate(QSerialPort.BaudRate.Baud115200)
        self.port_com_port.setParity(QSerialPort.Parity.NoParity)
        self.port_com_port.setDataBits(QSerialPort.DataBits.Data8)
        self.port_com_port.setStopBits(QSerialPort.StopBits.OneStop)

        self.port_com_port.open(QIODevice.ReadWrite)
        self.port_com_port.readyRead.connect(self.readFromSerial)

    def readFromSerial(self):
        print(self.port_com_port.readAll())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = QtSerialTest()
    app.exec()

I can confirm that after a restart, the function "readFromSerial" is never called, although the device sends.我可以确认重启后,function“readFromSerial”从未被调用,尽管设备发送。

EDIT: I forgot to mention: I compared the port-settings from program A and B, they are equal编辑:我忘了说:我比较了程序 A 和 B 的端口设置,它们是相等的

After some search, I could remove the workaround and it works now.经过一些搜索,我可以删除解决方法,现在它可以工作了。 I missed an important configuration-parameter.我错过了一个重要的配置参数。 After opening the QtSerialPort, self.port_com_port.setDataTerminalReady(True) needs to be called.打开QtSerialPort后,需要调用self.port_com_port.setDataTerminalReady(True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM