Qt串口错误 - 数据无法读取

时间:2013-11-08 21:26:53

标签: qt serial-port qtserialport

我正在尝试使用Qt SerialPort库读取串行端口。我可以使用HyperTerminal读取数据。

在Qt中,我使用以下代码尝试做同样的事情。 Qt说端口已正确打开,但由于某种原因,串口的bytesAvailable始终为0。

serial.setPortName("COM20");

if (serial.open(QIODevice::ReadOnly))
    qDebug() << "Opened port " << endl;
else
    qDebug() << "Unable to open port" << endl;

serial.setDataBits(QSerialPort::Data8);

serial.setParity(QSerialPort::EvenParity);

serial.setBaudRate(QSerialPort::Baud115200);


qDebug() << "Is open?? " << serial.isOpen();


// Wait unit serial port data is ready
while (!serial.bytesAvailable())
{
    //qDebug() << serial.bytesAvailable()<<endl;
    continue;
}

QByteArray data = serial.read(100);

qDebug() << "This is the data -" << data << endl;

serial.close();

相比之下,MATLAB代码具有与上面代码相​​同的结构,成功管理读取串口数据

%Serial Port Grapher - Shurjo Banerjee

s = serial('COM20');
s.BaudRate = 460800;
s.Parity = 'even';

try 
    input('Ready to begin?');
catch
end


fopen(s);

fh = figure();
hold on;

t = 1;

 while (s.BytesAvailable <= 0)
        continue
 end
 a = fread(s, 1)

 old_t = 1;
 old_a = a;

while true

   if (s.BytesAvailable > 0)
        a = fread(s, 1)

        figure(fh)
        t = t + 1;
        plot([old_t t], [old_a a]);
        old_t = t;
        old_a = a;
    end
end

fclose(s);

1 个答案:

答案 0 :(得分:0)

1)这是错误:https://codereview.qt-project.org/#change,47729

建议解决方案:


我在qserialport_win.cpp中更改了第161行:

return error;

return !error;

现在我的简化示例正常运作。


2)我也建议:

一步:打开端口:

            if (this->open(QIODevice::ReadWrite)) {
            } else {
                qDebug() << "\n Can't open port | " << this->errorString();
            }

两步:我建议检查参数设置:

            if (
                    this->setBaudRate(this->baudRate)
                    && this->setDataBits(this->dataBits)
                    && this->setParity(this->parity)
                    && this->setStopBits(this->stopBits)
                    && this->setFlowControl(this->flowControl)) {
                qDebug() << "\n[ info ]        Port settings successfully";
            } else {
                qDebug() << "\n[ error ]        Port settings failed";
            }

如果一切顺利,建议使用SIGNAL ReadyRead()和您的SLOT接收数据。