简体   繁体   中英

Serial Communication Timeout in QT with Arduino

I want to implement a timeout mechanism such that if the arduino doesn't read the command within one second, it results in a timeout and the new command is discarded and the program runs fine. But right now, the program hangs if any new command is sent during the execution of the old one.

This is the timeout section of my code:

QByteArray requestData = myRequest.toLocal8Bit();
    serial.write(requestData);
    if (serial.waitForBytesWritten(waitTime)) {
        if (serial.waitForReadyRead(myWaitTimeout)) {
            QByteArray responseData = serial.readAll();
            while (serial.waitForReadyRead(10))
                responseData += serial.readAll();
            QString response(responseData);
            emit this->response(response);
        } else {
            emit timeout(tr("Wait Read Request Timed Out %1")
                         .arg(QTime::currentTime().toString()));
        }
    } else {
        emit timeout(tr("Wait Write Request Timed Out %1")
                     .arg(QTime::currentTime().toString()));
    }

The timeout signal is connected to a slot that just prints the timeout message and does nothing. How can I fix this so that I can achieve what I target?

You are using blocking approach to transmit data via serial port. Unless you are using threads I don't see possibility to send any additional data during execution of previous loop. BTW: Your program, for example, will block indefinitely if Arduino manages to keep sending something within 10ms periods.

Add couple of QDebug() << "I'm here"; lines to check where your code gets stuck; it is possible that you are blocking somewhere outside code you pasted here. Alternative is to use debugger.

What if previous 'command' you tried to send is still in the buffer ? You'll end up filling output buffer. Check with QDebug how many bytes are in output buffer before writing more data to it. Buffer should be empty. (qint64 QIODevice::bytesToWrite() const).

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