I
I
Ilnur2018-08-20 13:19:24
Qt
Ilnur, 2018-08-20 13:19:24

Why does QSerialPort only read the first character?

Good afternoon
By means of QSerialPortInfo I receive possible COM ports.
If they are not busy, then I send bytes.
I get only one character.

for (const QSerialPortInfo &info : QSerialPortInfo::availablePorts()){
            if (!info.isBusy())
            {
                QSerialPort newSerialPort;
                newSerialPort.setPortName(info.portName());
                newSerialPort.setBaudRate(QSerialPort::Baud9600);
                newSerialPort.setStopBits(QSerialPort::OneStop);
                newSerialPort.setDataBits(QSerialPort::Data8);
                newSerialPort.setParity(QSerialPort::NoParity);
                newSerialPort.setFlowControl(QSerialPort::NoFlowControl);
                newSerialPort.open(QIODevice::ReadWrite);
                    QByteArray ba;
                    ba.resize(5);
                    ba[0] = 0x55;
                    ba[1] = 0x55;
                    ba[2] = 0x00;
                    ba[3] = 0x00;
                    ba[4] = 0xaa;
                    newSerialPort.write(ba);
                    QByteArray data = newSerialPort.readAll();
                    qDebug() << "data" << data; // выводит только первый символ
}
}

If I do all this without for (const QSerialPortInfo &info : QSerialPortInfo::availablePorts()){
Then I get a full answer
. What could be the reason?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilnur, 2018-08-21
@Il_noor

Many thanks to everyone)
But the solution
I took from here: doc.qt.io/qt-5/qtserialport-blockingmaster-example.html

portCOM->write(ba);
portCOM->waitForReadyRead(200);

QByteArray data = portCOM->readAll();
while (portCOM->waitForReadyRead(10))
data += portCOM->readAll();

D
Denis, 2018-08-20
@D3Nd3R

Use QSerialPort::waitForReadyRead() before reading from the port.
You can also implement asynchronous reading by writing a handler for the readyRead() signal .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question