Qt关闭串口前发送串口消息

Send a serial message before closing the serial port in Qt

我正尝试在 Qt 中为一个学术项目开发一个用户界面,该界面将串行消息发送到微控制器。不过,我正在努力关闭串行端口:用户界面应该在关闭串行端口之前向微控制器发送一条串行消息。这是管理此操作的代码部分:

device->write(QString("ABORT___").toStdString().c_str());
displayMessage("Disconnected");
deviceIsConnected = false;
device->close();
ui->PortComboBox->setEnabled(true);
ui->tabWidget->setEnabled(false);
ui->ConnectButton->setText("Connect");
ui->ConnectionStatus->setText("<span style=\" color:#e1d41f;\">DISCONNECTED</span>");

问题是此代码在实际发送消息之前关闭了端口,事实上,如果我尝试注释此行 device->close();,代码会按预期工作。似乎在发送消息之前端口已关闭,即使管理端口关闭的行在之后。 即使我尝试在某些 if 语句中嵌套 device->close(); 行,问题仍然存在。

你能帮帮我吗?

一旦 bytesWritten 信号发出,您应该关闭端口

或者您可以致电 waitForBytesWritten

For buffered devices, this function waits until a payload of buffered written data has been written to the device and the bytesWritten() signal has been emitted, or until msecs milliseconds have passed. If msecs is -1, this function will not time out. For unbuffered devices, it returns immediately.