我一直在研究向 LG 电视发送串行命令的项目。这是我的代码:
#include <QtSerialPort/QSerialPort>
#include <QTextStream>
#include <QCoreApplication>
#include <QFile>
#include <QStringList>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication coreApplication(argc, argv);
int argumentCount = QCoreApplication::arguments().size();
QStringList argumentList = QCoreApplication::arguments();
QTextStream standardOutput(stdout);
/*if (argumentCount == 1) {
standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
return 1;
}*/
QSerialPort serialPort;
QString serialPortName = "com3";
serialPort.setPortName(serialPortName);
serialPort.setBaudRate(QSerialPort::Baud9600);
serialPort.open(QIODevice::WriteOnly);
/*if (!serialPort.open(QIODevice::WriteOnly)) {
standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}*/
QFile dataFile("C:\\SerialCommand.dat");
if (!dataFile.open(QIODevice::ReadOnly)) {
standardOutput << QObject::tr("Failed to open file for reading") << endl;
return 1;
}
QByteArray writeData(dataFile.readAll());
dataFile.close();
if (writeData.isEmpty()) {
standardOutput << QObject::tr("Either no data was currently available on the standard input for reading, or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
qint64 bytesWritten = serialPort.write(writeData);
if (bytesWritten == -1) {
standardOutput << QObject::tr("Failed to write the data to port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
} else if (bytesWritten != writeData.size()) {
standardOutput << QObject::tr("Failed to write all the data to port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
} else if (!serialPort.waitForBytesWritten(5000)) {
standardOutput << QObject::tr("Operation timed out or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
return 1;
}
standardOutput << QObject::tr("Data successfully sent to port %1").arg(serialPortName) << endl;
return 0;
}
当我重新启动我的电脑时,我运行代码并且没有任何反应。之后,我打开 TeraTerm,发送文件,它就可以工作了(关闭电视 [不,它不切换])。然后我断开 TeraTerm 中的端口并再次运行我的代码,但这一次它也能正常工作!
我尝试使用我的代码在一次运行中多次发送文件。我尝试打开串口后等待了很长时间。我尝试多次发送文件并在发送之间等待并重新打开文件。没有任何效果。
TeraTerm 是一个开源项目,但它对我(一个新手程序员)来说太先进了,无法导航。这是 TeraTerm 项目页面的链接。如果您发现我的代码与 TeraTerm 的代码之间存在任何重大差异,我将非常感谢您指出这一点。