当前位置: 首页>>代码示例>>C++>>正文


C++ QSerialPort类代码示例

本文整理汇总了C++中QSerialPort的典型用法代码示例。如果您正苦于以下问题:C++ QSerialPort类的具体用法?C++ QSerialPort怎么用?C++ QSerialPort使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QSerialPort类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: switch

QString MainWindow::serialErrorString() const
{
    QSerialPort* serial = qobject_cast<QSerialPort*>(_ioDevice);
    switch(serial->error())
    {
        case QSerialPort::NoError:
            return "no error";
        case QSerialPort::DeviceNotFoundError:
            return "device not found";
        case QSerialPort::PermissionError:
            return "permission error";
        case QSerialPort::OpenError:
            return "device is already opened";
        case QSerialPort::FramingError:
            return "framing error";
        case QSerialPort::ParityError:
            return "parity error";
        case QSerialPort::BreakConditionError:
            return "break condition error";
        case QSerialPort::ReadError:
            return "read error";
        case QSerialPort::WriteError:
            return "write error";
        case QSerialPort::UnsupportedOperationError:
            return "unsupported operation error";
        case QSerialPort::UnknownError:
        default:
            return "unknown error";
    }
}
开发者ID:GlennVDLocht,项目名称:dash7-ap-open-source-stack,代码行数:30,代码来源:mainwindow.cpp

示例2: main

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 = argumentList.at(1);
    serialPort.setPortName(serialPortName);

    int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
    serialPort.setBaudRate(serialPortBaudRate);

    if (!serialPort.open(QIODevice::ReadOnly)) {
        standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    SerialPortReader serialPortReader(&serialPort);

    return coreApplication.exec();
}
开发者ID:Drakey83,项目名称:steamlink-sdk,代码行数:31,代码来源:main.cpp

示例3: tcgetattr

bool Ficgta01MultiplexerPlugin::detect( QSerialIODevice *device )
{
// The FIC needs a special line discipline set on the device.
    QSerialPort *port = qobject_cast<QSerialPort *>( device );
    if (port) {
        int discipline = N_TIHTC;
        ::ioctl(port->fd(), TIOCSETD, &discipline);
    }
    device->discard();
    int rc;
    struct termios t;
    rc = tcgetattr(port->fd(), &t);
    t.c_cflag |= CRTSCTS;
    rc = tcsetattr(port->fd(), TCSANOW, &t);


    // Issue an innocuous command to wake up the device.
    // It will respond with either "OK" or "AT-Command Interpreter ready".

    // We will do this up to 10 times as the modem is losing the first at
    // commands (due waking up)
    int attempts = 10;
    while (--attempts >= 0 && !QSerialIODeviceMultiplexer::chat( device, "ATZ"));


    // Issue the AT+CMUX command to determine if this device
    // uses GSM 07.10-style multiplexing.
#ifndef FICGTA01_NO_MUX
    return QGsm0710Multiplexer::cmuxChat( device, FICGTA01_FRAME_SIZE, true );
#else
    return true;
#endif
}
开发者ID:GodFox,项目名称:qtopia-ezx,代码行数:33,代码来源:ficgta01multiplexer.cpp

示例4: newSession

bool AtSessionManager::addSerialPort
        ( const QString& deviceName, const QString& options )
{
    // Bail out if the device is already bound.
    if ( d->serialPorts.contains( deviceName ) )
        return true;

    // Attempt to open the device.
    QSerialPort *port = QSerialPort::create( deviceName, 115200, true );
    if ( !port )
        return false;
    connect( port, SIGNAL(destroyed()), this, SLOT(serialPortDestroyed()) );

    // Zero reads on RFCOMM sockets should cause a close to occur.
    port->setKeepOpen( false );

    // Add the device to our list.
    d->serialPorts.insert( deviceName, port );
    registerTaskIfNecessary();

    // Wrap the device in a new session handler.  We hang it off the
    // serial port object so it will get cleaned up automatically
    // when removeSerialPort is called.
    AtFrontEnd *session = new AtFrontEnd( options, port );
    session->setDevice( port );
    emit newSession( session );
    return true;
}
开发者ID:Camelek,项目名称:qtmoko,代码行数:28,代码来源:atsessionmanager.cpp

示例5: run

void ConnectionThread::run()
{
    if(stepByStep)
        sendNextCommand = false;
    else
        sendNextCommand = true;

    QSerialPort serial;
    serial.setPortName(portName);
    if (!serial.open(QIODevice::ReadWrite))
    {
        emit error(tr("Can't open %1, error code %2").arg(portName).arg(serial.error()));
        return;
    }

    while (!quit) {
        if(stepByStep)
        {
            while(!sendNextCommand);
            mutex.lock();
            sendNextCommand = false;
            mutex.unlock();
        }
        // Envoi microcommande
        serial.write(test->recupProchaineMicrocommande().c_str());
        if(!serial.waitForBytesWritten(waitTimeout))
        {
            emit timeout(tr("Wait write microcommande timeout %1").arg(QTime::currentTime().toString()));
        }
        //Accusé de reception
        if(serial.waitForReadyRead(waitTimeout))
        {
            QByteArray received = serial.readAll();
            if(received.toStdString().compare(COMMANDE_RECEIVED) != 0)
            {
                emit error("Not wanted response");
            }
        }
        else
        {
            emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
        }
        //Pret a recevoir prochaine commande
        if(serial.waitForReadyRead(waitTimeout))
        {
            QByteArray received = serial.readAll();
            if(received.toStdString().compare(READY_FOR_NEXT_COMMAND) != 0)
            {
                emit error("Not wanted response");
            }
        }
        else
        {
            emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
        }
    }
}
开发者ID:cocosar07,项目名称:ProjetS4,代码行数:57,代码来源:connectionthread.cpp

示例6: onRxData

 void onRxData() {
    if (m_port.bytesAvailable() < 9) return;
    if (m_port.error() != QSerialPort::NoError)
       return;
    if (! check(m_port.peek(9)))
       return setIoStatus(ChecksumError);
    uint8_t dummy;
    m_str >> m_address >> dummy >> m_status >> dummy >> m_value;
    setIoStatus(Ok);
 }
开发者ID:KubaO,项目名称:stackoverflown,代码行数:10,代码来源:main.cpp

示例7: QSerialPort

PortSettings PositioningMethodSerialPortOptions::getPortSettings(const QString &APortName)
{
    PortSettings portSettings;
    OptionsNode node;
    if (Options::hasNode(OPV_POSITIONING_METHOD_SERIALPORT, APortName))
        node = Options::node(OPV_POSITIONING_METHOD_SERIALPORT, APortName);
    else
    {
        QSerialPort *serialPort = new QSerialPort(APortName);
        if (serialPort->open(QIODevice::ReadOnly))
        {
            portSettings.FBaudRate    = serialPort->baudRate();
            portSettings.FDataBits    = serialPort->dataBits();
            portSettings.FStopBits    = serialPort->stopBits();
            portSettings.FParity      = serialPort->parity();
            portSettings.FFlowControl = serialPort->flowControl();
            serialPort->close();
        }
        else // Failed to open the port
            node = Options::node(OPV_POSITIONING_METHOD_SERIALPORT, APortName);
        serialPort->deleteLater();
    }
    if (!node.isNull())
    {
        portSettings.FBaudRate = node.value("baud-rate").toLongLong();
        portSettings.FDataBits = (QSerialPort::DataBits)node.value("data-bits").toInt();
        portSettings.FStopBits = (QSerialPort::StopBits)node.value("stop-bits").toInt();
        portSettings.FParity = (QSerialPort::Parity)node.value("parity").toInt();
        portSettings.FFlowControl = (QSerialPort::FlowControl)node.value("flow-control").toInt();
    }
    return portSettings;
}
开发者ID:RoadWorksSoftware,项目名称:eyecu-qt,代码行数:32,代码来源:positioningmethodserialportoptions.cpp

示例8: foreach

void SerialSetup::GetSerialport()
{
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        qDebug() << "Name : " << info.portName();
        QSerialPort serial;
        serial.setPort(info);
        if (serial.open(QIODevice::ReadWrite))
            {
                serial.close();
                ui->SerialPort->addItem(info.portName());
            }
    }
开发者ID:damoyelang1992,项目名称:Qt-QRcodeSQLite,代码行数:12,代码来源:serialsetup.cpp

示例9: dlg

void MainWindow::on_connectAction_triggered(bool connect)
{
    if(connect)
    {
        ConnectDialog dlg(this);
        if(dlg.exec() == QDialog::Accepted)
        {
            if(dlg.connectionType() == Serial)
            {
                QSerialPort* serialPort = new QSerialPort(this);
                _ioDevice = serialPort;
                serialPort->setPort( dlg.serialPortInfo());
                if(serialPort->open(QIODevice::ReadWrite))
                {
                    // TODO hardcoded settings
                    if(!serialPort->setBaudRate(QSerialPort::Baud115200) ||
                        !serialPort->setDataBits(QSerialPort::Data8) ||
                        !serialPort->setParity(QSerialPort::NoParity) ||
                        !serialPort->setFlowControl(QSerialPort::NoFlowControl) ||
                        !serialPort->setStopBits(QSerialPort::TwoStop))
                    {
                        serialPort->close();
                        QMessageBox::critical(this, "Logger", "Can't configure serial port, reason: " + serialErrorString());
                        return;
                    }

                }
                else
                {
                    QMessageBox::critical(this, "Logger", "Serial port connection failed, reason: " + serialErrorString(), QMessageBox::Ok);
                    return;
                }
            }
            else if(dlg.connectionType() == File)
            {
                QFile* file = new QFile(dlg.fileName(), this);
                _ioDevice = file;
            }

            _logParser = new LogParser(_ioDevice, this);
            QObject::connect(_logParser, SIGNAL(logMessageReceived(QString)), SLOT(onLogMessageReceived(QString)));
            QObject::connect(_logParser, SIGNAL(packetParsed(Packet)), SLOT(onPacketParsed(Packet)));

           _logParser->setParent(0);
           _logParser->moveToThread(_parserThread);
            _parserThread->start();
            _logParser->openDevice();
        }
    }
    else
    {
        _ioDevice->close();
    }

    updateStatus();
}
开发者ID:GlennVDLocht,项目名称:dash7-ap-open-source-stack,代码行数:56,代码来源:mainwindow.cpp

示例10: main

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);


    QStringList argumentList = QCoreApplication::arguments();

    QSerialPort serialPort;
    QString serialPortName = "/dev/ttyUSB0"; // default
    int boudRate = QSerialPort::Baud115200;

    if (argumentList.size() == 2 ) {
        serialPortName = argumentList.at(0);
        boudRate = argumentList.at(1).toInt();
    }

    serialPort.setPortName(serialPortName);
    serialPort.open(QIODevice::ReadWrite);
    serialPort.setBaudRate(boudRate);
    serialPort.setDataBits(QSerialPort::Data8);
    serialPort.setParity(QSerialPort::NoParity);
    serialPort.setStopBits(QSerialPort::OneStop);
    serialPort.setFlowControl(QSerialPort::NoFlowControl);

    SerialPortReader serialPortReader(&serialPort, 8080);

    serialPortReader.showSerialInfo();


    return a.exec();
}
开发者ID:csavur,项目名称:bgServer,代码行数:31,代码来源:main.cpp

示例11: sendAbortCmd

void ScanUART::sendAbortCmd(QSerialPort &port)
{
    QByteArray abortCmd;
    abortCmd += 'a';
    port.setBaudRate(QSerialPort::Baud115200);
    port.write(abortCmd);
    port.waitForBytesWritten(100);
    int maxCnt = 20;
    int cnt=0;
    while(port.waitForReadyRead(100)) {
        port.readAll();
        cnt++;if(cnt>=maxCnt) break;
    }
}
开发者ID:atikbif,项目名称:relkonIDE,代码行数:14,代码来源:scanuart.cpp

示例12: discover

/**
 * This functions takes a serial port and tries if it can find a Kettler bike connected
 * to it.
 */
bool Kettler::discover(QString portName)
{
    bool found = false;
    QSerialPort sp;

    sp.setPortName(portName);

    if (sp.open(QSerialPort::ReadWrite))
    {
        m_kettlerConnection.configurePort(&sp);

        // Discard any existing data
        QByteArray data = sp.readAll();

        // Read id from bike
        sp.write("cd\r\n");
        sp.waitForBytesWritten(500);

        QByteArray reply = sp.readAll();

        reply.append('\0');

        QString replyString(reply);
        if (replyString.startsWith("ACK") || replyString.startsWith("RUN"))
        {
            found = true;
        }
    }

    sp.close();

    return found;
}
开发者ID:27sparks,项目名称:GoldenCheetah,代码行数:37,代码来源:Kettler.cpp

示例13: QWidget

JLWidget::JLWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::JLWidget)
{
    ui->setupUi(this);

    exusb = new ExUSB();
    exusb->start();
    exusbthread = new ExUSBThread(exusb);
    jl = new JLOpenCV();
    //img = new QImage(640,480,QImage::Format_RGB32);

    //connect(exusbthread,SIGNAL(exusbthread->GetFrameOK()),this,SLOT(flush_image));
    connect(exusbthread,SIGNAL(GetFrameOK(int)),this,SLOT(flush_image()),Qt::QueuedConnection);
    //connect(exusbthread,SIGNAL(exusbthread->GetFrameOK(int)),exusbthread,SLOT(test_recv()));
    //,Qt::QueuedConnection);
    //connect(this,SIGNAL(flush_image()),exusbthread,SLOT(GetFrameOK()),Qt::DirectConnection);
    //mVideoWidget.setParent(this);
    /*
    mVideoWidget = new QVideoWidget();
    mMediaPlayer = new QMediaPlayer;
    QMediaContent mp = QUrl::fromLocalFile("E:\\zlj_bd.mp4");
    mMediaPlayer->setMedia(mp);

    mMediaPlayer->setVideoOutput(mVideoWidget);
    //mVideoWidget->setBaseSize(1024,576);
    mVideoWidget->setGeometry(0,0,1024,576);
    mVideoWidget->show();
    mMediaPlayer->play();
    */
    // image
    img = new QImage(640,480,QImage::Format_RGB32);
    scence = new QGraphicsScene;

    QPainter mPainter(ui->histwidget);
    mPainter.setPen(Qt::blue);
    mPainter.drawText(rect(),Qt::AlignCenter,"Hello WOrld");



    // serialport
    QSerialPort *mPort = new QSerialPort();
    mPort->setPortName("COM4");
    mPort->setBaudRate(mPort->Baud115200);
    if (mPort->open(QIODevice::ReadWrite))
    {
        mPort->write("hello");
    }
}
开发者ID:secretan,项目名称:QtPrj,代码行数:49,代码来源:jlwidget.cpp

示例14: testBootMode

bool ScanUART::testBootMode(QSerialPort &port)
{
    bool foundFlag = false;
    SearchController contr;

    Request req;
    req.setNetAddress(0);

    port.setBaudRate(QSerialPort::Baud115200);
    CommandInterface* cmd = new GetCoreVersion();

    if(cmd->execute(req,port)){
        contr.setBaudrate(115200);
        if(QString(req.getRdData()).contains("boot")) contr.setBootMode(true);
        else contr.setBootMode(false);
        contr.setAsciiMode(false);
        contr.setNetAddress(0);
        contr.setUartName(pName);
        if(contr.getBootMode()) {
            emit plcHasBeenFound(contr);
            foundFlag = true;
        }
    }
    delete cmd;
    if(foundFlag) return true;
    return false;
}
开发者ID:atikbif,项目名称:relkonIDE,代码行数:27,代码来源:scanuart.cpp

示例15: scan

bool ScanUART::scan(QSerialPort &port)
{
    bool foundFlag = false;
    SearchController contr;
    float stepWidth = 100.0/(baudTable.count()*2);
    float currentPercent=0;
    for(int i=0;i<baudTable.count();i++) {

        Request req;
        req.setNetAddress(progAddr);

        port.setBaudRate(baudTable.at(i));
        CommandInterface* cmdBin = new GetCoreVersion();
        CommandInterface* cmdAscii = new AsciiDecorator(cmdBin);
        QVector<CommandInterface*> cmdList {cmdBin, cmdAscii};
        foundFlag = false;
        foreach(CommandInterface* cmd, cmdList) {
            if(cmd->execute(req,port)){
                contr.setBaudrate(baudTable.at(i));
                if(QString(req.getRdData()).contains("Relkon")) contr.setBootMode(false);
                else contr.setBootMode(true);
                if(dynamic_cast<AsciiDecorator*>(cmd)) contr.setAsciiMode(true);
                else contr.setAsciiMode(false);
                GetCoreVersion* coreCmd = dynamic_cast<GetCoreVersion*>(cmdBin);
                if(coreCmd) contr.setNetAddress(coreCmd->getNetAddress());
                else contr.setNetAddress(0);
                contr.setUartName(pName);

                // get canal name
                if(contr.getBootMode()==false) {
                    CommandInterface* cmdGetName = new GetCanName();
                    if(contr.getAsciiMode()) cmdGetName = new AsciiDecorator(cmdGetName);
                    if(cmdGetName->execute(req,port)) {
                        contr.setCanName(QString(req.getRdData()).remove("Canal:"));
                    }
                    delete cmdGetName;
                }

                emit percentUpdate(100);
                emit plcHasBeenFound(contr);

                foundFlag = true;


                break;
            }
            currentPercent+=stepWidth;
            emit percentUpdate(currentPercent);

        }
        delete cmdAscii; // cmdBin удаляется декоратором
        mutex.lock();
        if(stopCmd) {mutex.unlock();break;}
        mutex.unlock();
        if(foundFlag) break;
    }
    if(foundFlag) return true;
    return false;
}
开发者ID:atikbif,项目名称:relkonIDE,代码行数:59,代码来源:scanuart.cpp


注:本文中的QSerialPort类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。