简体   繁体   中英

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->setPortName("ttyUSB0");
serialPort->setParity(QSerialPort::NoParity);
serialPort->setBaudRate(QSerialPort::Baud9600, QSerialPort::AllDirections);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->setFlowControl(QSerialPort::NoFlowControl);
serialPort->open(QIODevice::ReadOnly);

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 (datas.at(i)) {
                qDebug() << datas[i];
            }
        }
    }

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

serialPort->close();
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM