QSerialPort - Reading cut

0

I am having problems to read whole lines from the serial port in linux. I have a gps that connects to the serial port and I can not get the lines read from it to arrive complete. I put the code that I have (taken from the Terminal Example Example of QT.) In that example, they send what they receive to a QPlainTextEdit, and they show the QPlainTextEdit so they are "pretty" the output ... but I need the complete line to process it Here is my code (it is worth clarifying that the new is done in another part of the code):

void MainWindow::openSerialPort()
{
    m_serial->setPortName("/dev/ttyUSB0");
    m_serial->setBaudRate(9600);
    connect(m_serial, &QSerialPort::readyRead, this, &MainWindow::readData);

    if (m_serial->open(QIODevice::Read)) {
        qDebug() << "Conectado Correctamente!";
    } else {
        qDebug() << "Error al conectar!";
    }
}

void MainWindow::readData()
{
    const QByteArray data = m_serial->readAll();
    qDebug() << data << endl;
}

And the output obtained is as follows:

  

Connected Properly!
  "DAA, -61.262786, -37.245445,587.6,0.1,288.6,40718,20505200,7 \ r \ n00,7 \ r \ nDATA, -61.262786, -37.245445,587.3,0.1,288.6,40718,20505000,7 \ r \ nDATA, -61.262786, -37.245445,587.6,0.1,288.6,40718,20505200,7 \ r \ n "

     

"St"

     

"arti"

     

"ng"

     

"to p"

     

"rubbing"

     

"ss .."

     

". \ r \ n"

     

"DAT"

     

"A, -6"

     

"1.26"

     

"2798"

     

", - 3"

     

"7.24"

     

"5452"

     

", 58"

     

"7.9,"

     

"0.5,"

     

"0.0,"

     

"4071"

     

"8,20"

     

"505"

     

"700.7 \ r \ n"

     

"DATA"

     

", - 61"

When in fact, I expected to obtain the same as the output of the Terminal example program that is shown below:

DATA,-61.262786,-37.245445,587.3,0.1,288.6,40718,20505000,7
DATA,-61.262786,-37.245445,587.6,0.1,288.6,40718,20505200,7
    
asked by Emiliano Torres 04.07.2018 в 22:55
source

2 answers

1

What seems to be happening is that readData is invoked on numerous occasions and on each occasion it contains only a fragment of the data ... you would have to prepare the reading routine to concatenate the successive readings and then that separates by line breaks:

void MainWindow::readData()
{
  static QString buffer;

  buffer += m_serial->readAll();

  while( int pos = buffer.indexOf("\r") != -1 )
  {
    qDebug() << buffer.left(pos);
    buffer = buffer.mid(pos+2);
  }
}
    
answered by 05.07.2018 / 08:34
source
-1

Googling a bit I came to the following solution:

void MainWindow::readData()
{
    while (m_serial->canReadLine()) 
        qInfo() << m_serial->readLine();
}

With those simple lines, we have in the buffer the complete line that arrives from the serial port. From what I understand, the serial port would be the one that does the buffering until the line is complete and just there you can do the readLine. To me, these lines solved a big problem.

    
answered by 05.07.2018 в 18:42