【问题标题】:QSerialPort ->write() or read() not as expected on clicked() signalQSerialPort ->write() 或 read() 与 clicked() 信号不同
【发布时间】:2021-04-05 00:28:56
【问题描述】:

我正在做一个 Qt5 项目。我有一个发出 clicked() 信号的按钮,它的插槽具有以下写入串行端口的代码:

void Dialog::on_startStream_clicked()
{
    QByteArray ba;
    if(esp->isOpen()){
        esp->write("1");
        if(esp->canReadLine()){
            ba = esp->readLine();
            ba.replace("\xFE", "");
            ba = ba.simplified();
            QString ba_with_time = stamp->currentDateTime().toString("MM.dd.yyyy hh:mm:ss  ");
            ba_with_time.append(ba);
            ui->output->appendPlainText(ba_with_time);
            qDebug() << ba_with_time;
        }
    }
}

与串口建立连接后,我第一次单击按钮时没有任何反应。后续点击正常工作。

我正在使用 PlatformIO 将 Arduino 代码上传到 ESP32,并且在我第一次发出命令后,在 PlatformIO 串行监视器中立即有输出,这让我认为问题出在我的 Qt 代码上。

如何解决它,以便 Qt 可以在第一次单击按钮时读取缓冲区?

【问题讨论】:

  • 如果你使用serialPort readyRead 信号,它每次都会工作。在您的代码中,第一次单击按钮的时间似乎错误。

标签: qt arduino


【解决方案1】:
QByteArry ba; // member of Dialog class

// connect the QSerialPort::readyRead() signal after creation of esp

connect(esp, &QSerialPort::readyRead, this, &Dialog::onDataReady);

...

void Dialog::on_startStream_clicked()
{
    if(esp->isOpen()){
        esp->write("1");
    }
}

// The "onDataReady()" is called every time you receive data via serial port

void Dialog::onDataReady()
{
    do{
        ba += esp->readAll(); // buffer received data
        int i = ba.indexOf("\n"); // i assume your message is \n terminated
        if(i != -1){ 
            QByteArray ba1 = ba.mid(0, i);
            // modify the data
            qDebug() << ba1;
            ba.remove(0, i); // remove message from receive buffer
        }
    } while(esp->bytesAvailable());
}

【讨论】:

  • 您可以添加超时,以防您在一定时间内没有收到“\n”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2021-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多