How can I wait until data comes in when reading data over Serial Port? QT C++

Viewed 47

I need to read ID data through Serial Port. When I send the ID read command with the leather port, the ID data comes to me a little late. Therefore, when I try to split the data and display it on the screen, it comes up blank and the application closes itself. How can I wait until the data comes in?

void productDetail::on_pushButton_clicked()
{
    QSerialPortInfo info;
        QList<QSerialPortInfo> infoList = QSerialPortInfo::availablePorts();

           foreach(info, infoList) QTextStream(stdout) << info.portName();
        QString curport = info.portName();


   serial.begin(curport, 9600, 8, 0, 1, 0, false);

   if(serial.isOpen()){
       qDebug()<<"serial open";
       QString sendWC= "WR+1121"; //Read ID command
       serial.send(sendWC);
       QString serialID = serial.getString();

        serialID = serialID.trimmed();
         QStringList buffer_split = serialID.split(",");

             ui->IDlabel->setText(buffer_split[2]; //when I write this program closes

             }
   }

}

error: ASSERT failure in QList::operator[]: "index out of range",

1 Answers

Qt's QIODevice provides a signal readyRead (https://doc.qt.io/qt-5/qiodevice.html#readyRead) which is emitted once every time new data is available for reading from the device.

In the productDetail class constructor, connect serial port readyRead signal to a slot.

connect(serial, &QSerialPort::readyRead, this, &productDetail::readData);

Define readData method as follows:

void productDetail::readData()
{
    const QByteArray data = m_serial->readAll();
}

For serial communication there is no guarantee that you will receive entire message data in a single read. I prefer to store the received data in a circular buffer and process the circular buffer in a separate slot.

Related