PDA

View Full Version : QSerialport read/readline/readall missing first char.



moman
8th October 2015, 22:17
I am an issue with reading from an RS232 serial port

I have an embedded app which is producing a null terminated string as follows.

##123456789$ (with zero at end)

I use...

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
connect(serial, SIGNAL(readyRead()), this, SLOT(readData())); // Confgure signal
}

to create the serial object.

The following code configures..

QString serialPortName = "COM11";
serial->setPortName(serialPortName);
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);


I open the port with thew following:

if (serial->open(QIODevice::ReadOnly))
{
ui->statusBar->showMessage(tr("Comms Connected"));
}


and use the following to print the resulting string on a linedit on the form for debuggting purposes..

void MainWindow::readData()
{
QByteArray data = serial->readLine(); //Get data from serial
ui->lineEdit->setText(data); //Put data on linedit

}

My issue is, I am ALWAYS losing the first charachter (The first # in this case)

I have also tried ReadAll and still loses the first character, whatever it is, however long the string.

To verify the RS232 data I am using RealTerm (a dedicated serial terminal program from sourceforge) which is receiving the full string, including the 2 x initial # chars.

It seems very reliable in that it only ever receives the second char onwards.

Any suggestions on why this is? (The baud rate is very low to be a synch problem) and how I can change this so it receives the FULL string?

Alas I am more an embedded assembler programmer, C++ is not my particular forte but Im learning. I used to use C-Builder 15-20 years ago and have forgotten lots but i think this is a QSerialport specific issue.

iain

ChrisW67
8th October 2015, 22:32
The bytes sent by the sender do not necessarily arrive together in a single invocation of the readdata(). When they arrive in several pieces the last piece will win in your code. Put a qDebug() in readdata() to dump the byte array to see how the bytes are actually received.

You need to buffer received bytes until you can see a full line in the buffer then process it.

moman
8th October 2015, 22:40
Hello,

Superb, thanks for the info, I quickly changed the display to ui->lineEdit->insert(data) instead of ui->lineEdit->setText(data) and I can now see all the chars. Now to buffer, thanks again..

iain