我尝试从设备接收串行消息,似乎readyRead()信号在串行缓冲区上出现的1,2或更多字符后被激活。
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timerTx = new QTimer(this);
timerTx->setInterval(100);
timer.start();
serialRx = new QSerialPort(this);
serialRx->setPortName("COM5");
serialRx->setBaudRate(QSerialPort::Baud9600);
serialRx->setParity(QSerialPort::NoParity);
serialRx->setDataBits(QSerialPort::Data8);
serialRx->setStopBits(QSerialPort::OneStop);
serialRx->setFlowControl(QSerialPort::NoFlowControl);
serialTx = new QSerialPort(this);
serialTx->setPortName("COM3");
serialTx->setBaudRate(QSerialPort::Baud9600);
serialTx->setParity(QSerialPort::NoParity);
serialTx->setDataBits(QSerialPort::Data8);
serialTx->setStopBits(QSerialPort::OneStop);
serialTx->setFlowControl(QSerialPort::NoFlowControl);
connect(serialRx, SIGNAL(readyRead()), this, SLOT(serialReceive()));
connect(timerTx, SIGNAL(timeout()), this, SLOT(serialSend()));
connect(ui->pushButton, SIGNAL(clicked()), timerTx, SLOT(start()));
}
void MainWindow::serialReceive()
{
QByteArray baRx, num, numOfMs;
qint64 time_ms;
baRx = serialRx -> readAll();
qDebug() << baRx;
time_ms = timer.elapsed();
counterRecDev++;
num = QByteArray::number(counterRecDev);
numOfMs = QByteArray::number(time_ms);
ui->receiveWindow->insertPlainText(num + "\t" + baRx + " \t " + numOfMs +
"\n" );
ui->receiveWindow -> moveCursor(QTextCursor::End);
}
我通过串口发送“@ Test $”消息,但我收到:“@”“T”“est”“%”其他时间:“@”“T”“es”“t”“%”
你能告诉我怎么解决吗?也许问题是我使用readyRead()信号?
最好的祝福。
使用readyRead()是可以的,但是在处理之前,您需要在代码中检查是否收到了所有预期的数据。这通常通过在消息中使用开始和停止字符并在处理之前检查接收到的数据是否包含两者来完成(看起来您已经在使用“@”和“$ for this)。并且,因为从QSerialPort读取将清除其缓冲区,您还需要在代码中缓冲接收的数据,直到它已准备好进行处理。您可以执行以下操作:
QByteArray rxBuffer;
void MainWindow::serialReceive()
{
rxBuffer.append(serialRx -> readAll());
while(rxBuffer.contains("@") && rxBuffer.contains("$")) {
QByteArray message;
// Discard any data preceding message start character
rxBuffer = rxBuffer.right(rxBuffer.length() - rxBuffer.indexOf("@"));
// Take first complete message from the buffer
message = rxBuffer.left(rxBuffer.indexOf("$") + 1);
// Remove extracted message from buffer
rxBuffer = rxBuffer.right(rxBuffer.length() - rxBuffer.indexOf("$") - 1);
// Your code here
}
}
我遇到了QSerialPort通过多个readyRead信号接收消息的问题。拥有一个累积缓冲区可以为您提供技巧,但您需要一个开始或结束标识符。