Qt5之串口操作总结

说明:版本为Qt5

1.在.pro文件中加入串口模块

QT += serialport

2.在.h文件中增加串口相关的头文件

#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>

3.在class中增减成员变量

QSerialPort *serialPort;                                            // 建议使用指针,不使用变量

4.串口初始化

serialPort = new QSerialPort(this);

5.打开串口

member->serialPort->setPortName(ui->comboUartPort->currentText());
member->serialPort->setBaudRate(ui->comboUartBps->currentText().toUInt());
member->serialPort->setDataBits(ui->comboUartDataBits->currentText().toUInt());
if (ui->comboUartParity->currentText() == tr("无"))
    member->serialPort->setParity(QSerialPort::NoParity);
else if (ui->comboUartParity->currentText() == tr("奇"))
    member->serialPort->setParity(QSerialPort::EvenParity);
else
    member->serialPort->setParity(QSerialPort::OddParity);
if (ui->comboUartStopBits->currentText() == "1")
    member->serialPort->setStopBits(QSerialPort::OneStop);
else if (ui->comboUartStopBits->currentText() == "2")
    member->serialPort->setStopBits(QSerialPort::TwoStop);
else
    member->serialPort->setStopBits(QSerialPort::OneAndHalfStop);
member->serialPort->setFlowControl(QSerialPort::NoFlowControl);
connect(member->serialPort, SIGNAL(readyRead()), this, SLOT(on_uart_read()));
if (member->uart->open(QIODevice::ReadWrite))
{
    // 打开成功
    ui->buttonUartOpen->setEnabled(false);
    ui->buttonUartClose->setEnabled(true);
}
else
{
    // 打开失败
    QMessageBox::critical(this, tr("错误"), tr("连接失败"), QMessageBox::Yes);
}

6.关闭串口

member->serialPort->close();
ui->buttonUartOpen->setEnabled(true);
ui->buttonUartClose->setEnabled(false);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值