TeraTerm串口使用与我的代码中的使用情况

时间:2016-03-01 15:36:26

标签: c++ qt serial-port teraterm

我一直致力于一个向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中的端口并再次运行我的代码,但这次它也能正常工作!

我尝试使用我的代码在一次运行中多次发送文件。打开串口后,我试着等了很长时间。我尝试多次发送文件并等待并在sendoff之间重新打开文件。没有任何效果。

TeraTerm是一个开源项目,但它对我(新手程序员)来说太先进了导航。This是TeraTerm项目页面的链接。如果您发现我的代码与TeraTerm之间存在任何重大差异,我将非常感谢您指出它。

0 个答案:

没有答案