Qt QSerialPort->;单击()信号时写入()或读取()与预期不符

Qt QSerialPort->;单击()信号时写入()或读取()与预期不符,qt,arduino,Qt,Arduino,我在做一个Qt5项目。我有一个发出clicked()信号的按钮,它的插槽中有以下代码写入串行端口: void Dialog::on_startStream_clicked() { QByteArray ba; if(esp->isOpen()){ esp->write("1"); if(esp->canReadLine()){ ba = esp->readLine();

我在做一个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;
        }
    }
}
void Dialog::在\u startStream\u clicked()上
{
QByteArray ba;
如果(esp->isOpen()){
esp->写入(“1”);
如果(esp->canReadLine()){
ba=esp->readLine();
ba.替换(“\xFE”,”);
ba=ba.simplified();
QString ba_with_time=stamp->currentDateTime().toString(“MM.dd.yyyy hh:MM:ss”);
带时间的ba_。追加(ba);
用户界面->输出->添加纯文本(带时间的ba_);
qDebug()
QByteArry ba;//对话框类的成员
//创建esp后,连接QSerialPort::readyRead()信号
连接(esp和QSerialPort::readyRead、this和Dialog::onDataReady);
...
void Dialog::在\u startStream\u clicked()上
{
如果(esp->isOpen()){
esp->写入(“1”);
}
}
//每次通过串行端口接收数据时,都会调用“onDataReady()”
void Dialog::onDataReady()
{
做{
ba+=esp->readAll();//缓冲区接收到的数据
int i=ba.indexOf(“\n”);//我假定您的消息已\n终止
如果(i!=-1){
QByteArray ba1=ba.mid(0,i);
//修改数据
qDebug()字节可用();
}
QByteArry ba;//对话框类的成员
//创建esp后,连接QSerialPort::readyRead()信号
连接(esp和QSerialPort::readyRead、this和Dialog::onDataReady);
...
void Dialog::在\u startStream\u clicked()上
{
如果(esp->isOpen()){
esp->写入(“1”);
}
}
//每次通过串行端口接收数据时,都会调用“onDataReady()”
void Dialog::onDataReady()
{
做{
ba+=esp->readAll();//缓冲区接收到的数据
int i=ba.indexOf(“\n”);//我假定您的消息已\n终止
如果(i!=-1){
QByteArray ba1=ba.mid(0,i);
//修改数据
qDebug()字节可用();
}

如果使用serialPort readyRead信号,则每次都有效。在您的代码中,第一次单击按钮时似乎计时错误。如果使用serialPort readyRead信号,则每次都有效。在您的代码中,第一次单击按钮时似乎计时错误。您可以添加超时,以防在一定的时间。您可以添加超时,以防在一定的时间内没有收到“\n”。
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());
}