gpt4 book ai didi

c++ - while循环中的QSerialPort?

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:55 25 4
gpt4 key购买 nike

我有一个通过 RS-232 将数据发送到 super 终端的功能。该函数在 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();
}

最佳答案

您的代码存在以下缺陷:

1) 你不处理错误。

2)你没有检查写操作的返回值。

3) 在再次编写之前,您似乎没有以编程方式等待。这是不正确的。使用同步 waitForBytesWritten 或异步 bytesWritten 信号为下一次写入亮起绿灯。

最关键的可能是最后一点。如何发送数据将导致“随机”行为。在这种特殊情况下,它可能会按顺序发送,因为等待输入可能会花费您更长的时间,但它仍然不是编写稳定和健壮的代码。

关于c++ - while循环中的QSerialPort?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com