Reputation: 2050
I'm going to write 5 bytes of data to a COM port and expect to receive 11 with the last byte of 0xFF to receive. I store the receiving bytes in pantilt_value
variable.
This is a code which works: (I receive the 11 bytes as expected with the last byte of 0xFF)
_port->write(data_pantilt, 5);
QByteArray pantilt_value = _port->readAll();
while (_port->waitForReadyRead(100))
pantilt_value.append(_port->readAll());
This is a code which doesn't work: (I receive just a first 2 bytes)
_port->write(data_pantilt, 5);
char d;
QByteArray pantilt_value;
while (_port->waitForReadyRead(100)){
_port->read(&d,1);
pantilt_value.append(d);
if (d == 0xff)
break;
}
Can you explain why the second code doesn't work.
Upvotes: 0
Views: 2131
Reputation: 2050
It seems that, The first time you call waitForReadyRead()
to check if there is a data on serial port to read, it returns true
, but you should read the whole data on the serial port after you call that method because if you fail to read the whole data after calling waitForReadyRead()
, next time you call that method, it returns false
, although there is still some data left to read from the port.
So my second code should be changed to something like this:
_port->write(data_pantilt, 5);
char d;
QByteArray pantilt_value;
while(_port->waitForReadyRead(100)){
while (_port->bytesAvailable() > 0){
_port->read(&d,1);
pantilt_value.append(d);
if (d == 0xff)
break;
}
}
Upvotes: 1
Reputation: 12931
waitForReadyRead()
returns true
only when there is new data available. In your second case, the while loop has time to execute twice before all data is received. Use QSerialPort::bytesAvailable
to see how much data there is to be read.
Upvotes: 1