luca_trep luca_trep - 26 days ago 17x
C++ Question

How to read data from the serial port in QT?

I am creating a script in QT for reading the format packages (AA), (BB), etc from serial port. I open the serial port, but when I go to check inside the QByteArray values, comes back that I could not read any value.

This is my code

QSerialPort *serialPort = new QSerialPort();
serialPort->setBaudRate(QSerialPort::Baud9600, QSerialPort::AllDirections);

if (serialPort->isOpen()) {
qDebug() << "Serial port is open...";
QByteArray datas = serialPort->readAll();
if (datas.size() == 0) {
qDebug() << "Arrived data: 0";
} else {
for (int i = 0; i < datas.size(); i++){
if ( {
qDebug() << datas[i];

} else {
qDebug() << "OPEN ERROR: " << serialPort->errorString();

qDebug() << "...serial port is closed!";

return 0;


You called readAll() immediately after open(). It probably took the computer a few nanoseconds to get from one to the other.

At 9600 baud, each byte of data takes slightly more than one millisecond to transfer. It would be absolutely impossible for any data to have arrived in that short an interval, so that's why you got no data.

Serial ports don't begin buffering incoming data until you open them (how could they, what baud rate and other settings would be used for receiving and buffering when no program has the port open?)

Use either a blocking read function of some sort (such as readLine()) or an event loop that reacts to data when it arrives.