PDA

View Full Version : qserialport and reading bytes



gab74
14th February 2014, 16:20
Good Morning,
i'm new in RS232 Programming.

I need to read data from a serial RS232 hardware.
The hardware can send 2 types of messages with a variable size
the first is 20 bytes (binary notation)
the other is 15 bytes. (binary notation)
Every message has LF in the last byte.

What is the best way to read theese data and reconstruct the messages ?

Is there any example showing how to read from a serial a variable number of bytes ?

i see :
QByteArray inByteArray = serial->readAll();

but in these way i dont' know how many bytes are read...and how to find the LF character to build the message to decode.
I think the readAll can also contains pieces of two messages...

Thanks in advance

to init the serial i use :

void MainWindow::initSerialPort()
{
serial->setPort("COM1");
if (serial->open(QIODevice::ReadWrite))
{
serial->setRate(SerialPort::Rate19200);
serial->setDataBits(SerialPort::Data8);
serial->setParity(SerialPort::NoParity);
serial->setStopBits(SerialPort::OneStop);
serial->setFlowControl(SerialPort::NoFlowControl);
}

else {
serial->close();
QMessageBox::critical(this, tr("Error"),
tr("Can't configure the serial port: %1,\n"
"error code: %2")
.arg("COM1").arg(serial->error()));
ui->statusBar->showMessage(tr("Open error"));
}

}

anda_skoa
14th February 2014, 17:30
i see :
QByteArray inByteArray = serial->readAll();

but in these way i dont' know how many bytes are read

QByteArray::count(), QByteArray::size() or QByteArray::length()
Your choice :-)



...and how to find the LF character to build the message to decode.

QByteArray::indexOf()

Cheers,
_

gab74
14th February 2014, 18:12
Ok in this way i can parse the received array of bytes and find the initial and final characher to identify a message.

Do you think is this the best solution ?

In onother way, I can read one byte at time...and parse one byte ... ?? What do you think about this ?

Thank you very much !!!

anda_skoa
14th February 2014, 21:11
The QSerialPort class will very likely have an internal buffer, so reading byte-per-byte shouldn't be that much different.

I think this will mostly be a matter of what you find easier to implement.

Cheers,
_