【发布时间】:2023-03-21 01:00:01
【问题描述】:
我有一个通过 RS-232 向超级终端发送数据的功能。该函数在 while 循环之外正常工作,但是,在 while 循环中,它仅在第一次发送之后它不发送任何内容。
qDebug() << MESSAGE;
int choice;
std::cin >> choice;
while( choice != 3 )
{
switch (choice)
{
case 1:
// Ready to send data
port->write("QSerial Port!\r\n");
break;
case 2:
qDebug() << "Todo...";
break;
case 3:
break;
default:
qDebug() << "Invalid Choice ...";
}
qDebug() << MESSAGE;
std::cin >> choice;
}
编辑:
#include <QCoreApplication>
#include <iostream>
#include <QDebug>
#include <QSerialPort>
const char MESSAGE[] = "\n----- New Menu ----"
"\n1- Send Data \n"
"2- Receive Data \n"
"3- Quit: \n";
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QSerialPort *port = new QSerialPort;
port->setPortName("COM4");
// Check the validity of the port
if ( !port->open(QIODevice::ReadWrite) )
{
qDebug() << "\nError: " << port->portName() << " port can't be opened ...";
return -1;
}else{
qDebug() << '\n' << port->portName() << " port has been opened successfully ...";
port->setBaudRate(QSerialPort::Baud9600);
port->setStopBits(QSerialPort::OneStop);
port->setDataBits(QSerialPort::Data8);
port->setParity(QSerialPort::NoParity);
port->setFlowControl(QSerialPort::NoFlowControl);
qDebug() << port->portName() << " port has been configured correctly ...";
}
qDebug() << MESSAGE;
int choice;
std::cin >> choice;
while( choice != 3 )
{
switch (choice)
{
case 1:
{
// Ready to send data
if ( port->write("QSerial Port!\r\n", qstrlen("QSerial Port!\r\n")) == -1)
{
qDebug() << port->errorString();
}
//port->bytesWritten(strlen("QSerial Port!\r\n"));
port->waitForBytesWritten(-1);
//qDebug() << port->errorString();
}
break;
case 2:
qDebug() << "Todo...";
break;
case 3:
break;
default:
qDebug() << "Invalid Choice ...";
}
qDebug() << MESSAGE;
std::cin >> choice;
}
qDebug() << "\n Goodbye ....";
port->close();
delete port;
return app.exec();
}
【问题讨论】:
-
请显示
port->errorString()的输出。另外,请说明如何配置 qtserialport 对象,如何打开它。您使用的是 QtSerialPort 5.2.1,对吗? -
if ( port->write("QSerial Port!\r\n", qstrlen("QSerial Port!\r\n")) == -1) { qDebug() << port->errorString(); } -
这是我检查错误的功能,但我什么也没得到。我不认为有错误,但是,我猜你说的是对的,那就是发送下一个数据的等待时间问题。
-
这是哪个操作系统?它是 32 位还是 64 位?是 QtSerialPort 5.2.1 还是 Qt 4? USB 串口还是原生?
-
64 位 Windows,QtSerialPort 5.2.1。虚拟串口驱动
标签: c++ qt qt5 qtcore qtserialport