简体   繁体   English

使用Arduino在QT中进行串行通信超时

[英]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. 我想实现一个超时机制,以便如果arduino在一秒钟内未读取该命令,则会导致超时,并且新命令将被丢弃,并且程序可以正常运行。 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. timeout信号连接到仅打印超时消息且不执行任何操作的插槽。 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. 顺便说一句:例如,如果Arduino设法在10ms的时间内继续发送某些内容,则您的程序将无限期地阻塞。

Add couple of QDebug() << "I'm here"; 添加几个QDebug()<<“我在这里”; 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. 在将更多数据写入输出缓冲区之前,请使用QDebug检查输出缓冲区中有多少字节。 Buffer should be empty. 缓冲区应该为空。 (qint64 QIODevice::bytesToWrite() const). (qint64 QIODevice :: bytesToWrite()常量)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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