问题
I have a very strange issue, which has been driving me mad for the last two days.
I have a serial device (LS 100 Photometer) which I am trying to control. Using a terminal (termite) set up with the correct parameters, I can send the command ("MES"), followed by the delimeter (CR LF), and I get back some measurement data as expected.
The problem is, from Qt, I do not get any data returned. Using a sniffer program, I have confirmed that I am sending the exact same 5 bytes (MES CR LF) as the terminal is sending, and with the same port setup.
If I change the flow control to "NoFlowControl" then I can get some data back, but it appears to be meaningless and is just one random byte. In any case the device documentation says to use RTS/CTS and that is what the terminal (termite) is set up to use.
Also, if I use the Qt serialport example terminal, I get the same issue where I can't get the device to return data. I have also tried using C# and have had the exact same issue. The only thing that seems capable of communicating with the instrument is the Termite terminal.
Qt Code:
port.setPortName(ui->cmbPort->currentText());
port.setBaudRate(QSerialPort::Baud4800);
port.setDataBits(QSerialPort::Data7);
port.setParity(QSerialPort::EvenParity);
port.setStopBits(QSerialPort::TwoStop);
port.setFlowControl(QSerialPort::HardwareControl);
if (!port.open(QIODevice::ReadWrite))
{
connected = false;
QMessageBox::information(this, "Failed To Open", "Failed to open the serial port");
ui->statusBar->showMessage("Connection to " + ui->cmbPort->currentText() + " failed...");
}
else
{
connected = true;
ui->statusBar->showMessage("Connected to " + ui->cmbPort->currentText() + "...");
}
QByteArray cmdB;
cmdB[0] = 0x4d;
cmdB[1] = 0x45;
cmdB[2] = 0x53;
cmdB[3] = 0x0d;
cmdB[4] = 0x0a;
qint64 r = port.write(cmdB.data(), cmdB.size());
qDebug() << "Written: " << r;
Then the ReadData function which is called on ReadyRead or every 100ms:
QByteArray data = port.readAll();
if (data.count() != 0)
{
qDebug() << "Read " << data.size() << " bytes";
QString str = QString(data);
ui->txtOutput->append(str);
}
Any help would be much appreciated, I'm running out of hair to pull out...
回答1:
Finally worked it out.
Even though the documentation says to use RTS/CTS, and the terminal program (termite) uses RTS/CTS, the solution was to turn off flow control in the Qt application (i.e. NoFlowControl), then turn on the RTS line manually just before sending data, like this:
port.setRequestToSend(true);
qint64 r = port.write(cmdB.data(), cmdB.size());
port.waitForBytesWritten(5000);
qDebug() << "Written: " << r;
来源:https://stackoverflow.com/questions/40042099/serial-comms-not-working-through-qserialport-qt-but-is-working-via-terminal-t