Qt 串口通讯

【QSerialPort】

       该类提供访问串口的功能。你可以使用QSerialPortInfo帮助类获取系统上可用的串口的信息,可以枚举系统上存在的所有串口。通过该类你可以获取串口的正确名称。你可以传递一个该类的对象作为setPort()或者setPortName()方法的参数指定想要访问的串口设备。
       在设置完了串口,你就可以以只读或者只写或者读写模式调用open()方法打开串口。
注意:串口都是以互斥的方式访问,这也就是说我们不能打开一个已经打开的串口。
        成功打开之后,QSerialPort尝试着获取串口当前的配置并初始化它。你也可以使用setBaudRate(),setDataBits(),setParity(),
setStopBits()

和setFlowControl()方法重新配置它。控制管脚的状态是根据isDataTerminalReady(),isRequestToSend()和pinoutSignals()决定的。要改变控制信息,可以使用如下方法:setDataTerminalReady()和setRequestToSend()。

        一旦你知道了串口可用于读或者写,你就可以调用read()或者write()方法。可选的还有readline()和readAll()方法。如果数据不能在一次读完,那么剩下的数据接下来就会存在QSerialPort的内部缓冲区中。你可以使用setReadBufferSize()方法设置缓冲区的大小。可以使用close()方法来关闭串口和取消I/O操作。
看看下面的示例:

[cpp]  view plain copy
  1. "font-family:Verdana;font-size:18px;">int numRead = 0, numReadTotal = 0;  
  2. char buffer[50];  
  3.   
  4.   
  5. forever {  
  6.     numRead  = serial.read(buffer, 50);  
  7.   
  8.   
  9.     // Do whatever with the array  
  10.   
  11.   
  12.     numReadTotal += numRead;  
  13.     if (numRead == 0 && !serial.waitForReadyRead())  
  14.         break;  
  15. }  
         在串口连接被关闭或者出现错误的时候,waitForReadyRead()就会返回false。
         阻塞的串口编程与非阻塞的串口编程是不一样的。阻塞的串口不许要事件循环,需要的代码很少。然而,在一个GUI应用程序中,阻塞的串口操作应该仅仅在非GUI线程中使用,避免用户界面冻结。对于这一点,详细信息可以查看示例程序。
         QSerialPort类可以跟QTextStream和QDataStream的流操作一起使用(operator<<()和operator>>())。这里需要注意一件事:使用操作符operator>>()的重载函数读取之前请确保有足够的数据可用。

【QSerialPortInfo】

提供系统中已存在的串口信息。
使用该类的静态函数获取一系列的QSerialPortInfo对象。列表中的每一个QSerialPort对象都代表了一个单独的串口,可以用于获取串口名、

系统路径、描述以及制造商等信息。QSerialPortInfo类也可以作为QSerialPort类的setPort()方法的一个输入参数。


1. 在comobox中显示可用串口名称


    ui->serialPortInfoListBox->clear();
    static const QString blankString = QObject::tr("N/A");
    QString description;
    QString manufacturer;
    QString serialNumber;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        QStringList list;
        description = info.description();
        manufacturer = info.manufacturer();
        serialNumber = info.serialNumber();
        list << info.portName()
             << (!description.isEmpty() ? description : blankString)
             << (!manufacturer.isEmpty() ? manufacturer : blankString)
             << (!serialNumber.isEmpty() ? serialNumber : blankString)
             << info.systemLocation()
             << (info.vendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : blankString)
             << (info.productIdentifier() ? QString::number(info.productIdentifier(), 16) : blankString);

        ui->serialPortInfoListBox->addItem(list.first(), list);

2. 打开并初始化串口

void MainWindow::openSerialPort()
{
    SettingsDialog::Settings p = settings->settings();
    
my_serialport= new QSerialPort();
    my_serialport->setPortName(ui->comboBox->currentText());
    my_serialport->setBaudRate(QSerialPort::Baud9600);
    my_serialport->setDataBits(QSerialPort::Data8);
    my_serialport->setParity(QSerialPort::NoParity);
    my_serialport->setStopBits(QSerialPort::OneStop);
    my_serialport->setFlowControl(QSerialPort::NoFlowControl);

    if (serial->open(QIODevice::ReadWrite)) {
            console->setEnabled(true);
            console->setLocalEchoEnabled(p.localEchoEnabled);
            ui->actionConnect->setEnabled(false);
            ui->actionDisconnect->setEnabled(true);
            ui->actionConfigure->setEnabled(false);
            ui->statusBar->showMessage(tr("Connected to %1 : %2, %3, %4, %5, %6")
                                       .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                                       .arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));
    } else {
        QMessageBox::critical(this, tr("Error"), serial->errorString());

        ui->statusBar->showMessage(tr("Open error"));
    }
}

3. 关闭串口

void MainWindow::closeSerialPort()
{
    serial->close();
    console->setEnabled(false);
    ui->actionConnect->setEnabled(true);
    ui->actionDisconnect->setEnabled(false);
    ui->actionConfigure->setEnabled(true);
    ui->statusBar->showMessage(tr("Disconnected"));
}

4.收发数据

信号槽:错误处理、读、写

    connect(serial, SIGNAL(error(QSerialPort::SerialPortError)), this,
            SLOT(handleError(QSerialPort::SerialPortError)));
    connect(serial, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(console, SIGNAL(getData(QByteArray)), this, SLOT(writeData(QByteArray)));

void MainWindow::readData()
{
    QByteArray data = serial->readAll();

    insertPlainText(QString(data));

    QScrollBar *bar = verticalScrollBar();
    bar->setValue(bar->maximum());
}


void MainWindow::writeData(const QByteArray &data)
{
    serial->write(data);
}


3. 关闭串口

你可能感兴趣的:(Qt 串口通讯)