[Solved] qtserialport read problem.



  • i can write to the serial port with the code i have below.
    i was wondering why am i not getting a response from the serial device.
    could somebody let me know what i am doing wrong thanks.

    @void MainWindow::ExitSurfaceMode()
    {
    QSerialPort serial;
    QString text("\\.\");
    text.append(ui->serialport->currentText());

    qDebug() << text;
    serial.setPortName(text);
    
    if (serial.open(QIODevice::ReadWrite))
    {
        serial.setBaudRate(QSerialPort::Baud9600);
        serial.setDataBits(QSerialPort::Data8);
        serial.setParity(QSerialPort::NoParity);
        serial.setStopBits(QSerialPort::OneStop);
        serial.setFlowControl(QSerialPort::NoFlowControl);
    
        SerialCommands start;
        std::vector<char> exit_mode = start.ExitCommand();
        QByteArray latin = QByteArray::fromRawData(exit_mode.data(),exit_mode.size());
        qDebug() << "exit command sent";
        qDebug() << latin;
    
        serial.write(latin);
        Sleep(500);
        QString data = serial.readAll();
        qDebug() << "This is the data -" << data << endl;
        serial.close();
    }
    

    }
    @



  • @
    ...
    serial.write(latin);
    serial.waitForBytesWritten(500);
    serial.waitForReadyRead(500);
    QString data = serial.readAll();
    ...
    @

    Of course, need to add a check for the returns values.

    BTW: See "examples":https://qt.gitorious.org/qt/qtserialport/source/dda7449d18cf8aaa542f869dcaea28634d21ecb0:examples/serialport.



  • use asynchronous receive methods
    to receive data efficiently



  • i tried to use the following

    @serial.waitForBytesWritten(500);
    serial.waitForReadyRead(500);@

    i received the data but it is not reliable. sometimes i get the whole message sometimes i only get part of the response.



  • Nobody guarantees that you will receive at once all package of data (1 byte? 15 bytes? 1000 bytes? 100000 bytes?).

    It is necessary to do waiting of expected number of bytes, like:

    @
    ...
    for (;;) {
    bool ret = serial.waitForReadyRead(500); // wait at least one byte available
    if (ret) {

        qint64 bav = serial.bytesAvailable();
        if (bav < expected)
            continue;
    
        QByteArray recvData = serial.read(expected);
    
        // do something
    
    } else {
        // error or timeout, no more bytes received
    
        // do something
    
    }
    

    }
    ...
    @

    But in any case is better to use the async approach instead of sync.



  • thanks i am receving data reliably now. :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.