I'm new in Qt and have some troubles in using Qserialport. I need to receive and manage data packets from an auto pilot and show them on a kind of compass. but I don't know how to receive data in a thread and use them in my main program. I know how to use Qserialport and I did use thread before. but now I don't know how to use them together properly. I really need some example code. any answer can help. and sorry if my english language is not so good.
Asked
Active
Viewed 6,692 times
1 Answers
1
You can read data in an asynchronous way. Just connect the readyRead()
signal of QSerialPort
to a slot. readyRead()
is emitted whenever new data is available :
connect(&serial, SIGNAL(readyRead()), this, SLOT(readData()));
readData()
is a slot that is called everytime QSerialPort
emits the readyRead()
signal. readData()
appends any available data to a QByteArray
class member :
void MyClass::readData()
{
receivedData.append(serial.readAll());
if(receivedData.count()>=someAmount)
{
//Use data and remove used data from receivedData
...
}
}

Nejat
- 31,784
- 12
- 106
- 138
-
thank you for answer it's really help. but i have another question. when i use readAll() it will read all incoming data and store them in QbyteArray, right? now how can i manage this data and pass some bytes of them to my main program parameters? – Sep 23 '14 at 06:52
-
Yes you read all data and store it in a `QByteArray`. What do you mean by "main program parameters"? – Nejat Sep 23 '14 at 07:23
-
the hole packet read in a thread and stored in QByteArray. now my question is how can I manage this for example 48 byte packet data and pass 4 bytes of it to for example a float in my UI? – Sep 23 '14 at 07:37
-
and I have another question. in readData() i don't get what receivedData.append do? are you define receivedData else where? – Sep 23 '14 at 07:41
-
`receivedData` is a class member of type `QByteArray`. You should define it in .h file. Converting some bytes to an other type like int depends on the endianness of the protocol. You can shift an int variable 8 bites and add a byte value to it and repeat it four times. – Nejat Sep 23 '14 at 07:48