Qt入门及C++复习(适合新手--5)案例:串口调试助手

QSerialPortInfo

您可以使用QSerialPortInfo辅助类获取有关可用串行端口的信息,该类允许枚举系统中的所有串行端口。

使用静态函数QList<QSerialPortInfo> availablePorts()生成QSerialPortInfo对象列表。列表中的每个QSerialPortInfo对象代表一个串行端口,可以查询端口名称、系统位置、描述和制造商。QSerialPortInfo类也可以用作QSerialPort类的setPort()方法的输入参数。您也可以将辅助类的对象作为参数传递给setPort()或setPortName()方法,以分配所需的串行设备。

设置端口后,您可以使用open()方法以只读(r/o)、只读(w/o)或读写(r/w)模式打开它。


QSerialPort

成功打开后,QSerialPort会尝试确定端口的当前配置并初始化自身。您可以使用setBaudRate()、setDataBits()、setParity()、setStopBits()和setFlowControl()方法将端口重新配置为所需的设置。

一旦你知道端口已经准备好读或写,你就可以使用read()或write()方法。或者,也可以调用readLine()和readAll()方便方法。如果不是一次读取所有数据,则剩余数据将在以后可用,因为新的传入数据将附加到QSerialPort的内部读取缓冲区。您可以使用setReadBufferSize()限制读取缓冲区的大小。

[signal]void QIODevice::readyRead()

每当有新数据可从设备的当前读取通道读取时,都会发出一次此信号。

QByteArray QIODevice::readAll()

从设备中读取所有剩余数据,并将其作为字节数组返回。 此功能无法报告错误;返回空的QByteArray可能意味着当前没有可供读取的数据,或者发生了错误。


QString

int QString::toInt(boolok=nullptr,int base=10)const

*将字符串返回转换为进制为base的int类型数,默认值为10,必须介于2和36之间,或0。如果转换失败,则返回0。 如果base为0,则使用C语言约定:如果字符串以“0x”开头,则使用base 16;如果字符串以“0”开头,则使用基数8;否则使用基座10。

QByteArray QString::toLatin1()const

返回字符串的Latin-1表示形式,作为QByteAarray。

QString QString::number(long n,int base=10)

根据指定的进制base返回与数字n等效的字符串。 默认情况下,base为10,必须介于2和36之间。对于10以外的基数,n被视为无符号整数。

long a = 63;
QString s = QString::number(a, 16);             // s == "3f"
QString t = QString::number(a, 16).toUpper();     // t == "3F"

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QtSerialPort/QtSerialPort>
#include <QTimer>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void TimerEvent();

    void serialPort_readyRead();//从设备中读取所有剩余数据,并将其作为字节数组返回。

    //接收设置
    void on_checkBox_clicked();

    void on_checkBox_2_clicked();

    void on_checkBox_3_clicked();


    void on_pushButton_clicked();//打开串口

    void on_pushButton_2_clicked();//发送

    void on_pushButton_3_clicked();//清空接受区

    void on_pushButton_4_clicked();//清空发送区

private:
    Ui::Widget *ui;
    QTimer *timer;
    QStringList portStringList;
    QSerialPort *serial;
    QString Receivetext, Sendtext;
    long Receive_Byte, Send_Byte;
};

#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <QMessageBox>

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

    resize(1060, 800);
    setWindowTitle("串口调试助手");

    //使用定时器,获取设备连接的串口信息
    timer = new QTimer(this);
    timer->start(500);
    connect(timer, &QTimer::timeout, this, &Widget::TimerEvent);

    serial = new QSerialPort(this);

    //设置默认参数
    ui->comboBox_2->setCurrentIndex(5);
    ui->comboBox_3->setCurrentIndex(3);
    ui->comboBox_4->setCurrentIndex(2);
    ui->comboBox_5->setCurrentIndex(0);

    Receive_Byte = 0;
    Send_Byte = 0;
    
    //获取串口数据
    connect(serial, QSerialPort::readyRead, this, &Widget::serialPort_readyRead);
    ui->checkBox->setCheckState(Qt::Checked);
}

Widget::~Widget()
{
    delete ui;
}

//自动识别串口
void Widget::TimerEvent()
{
    QStringList newPortStringList;
    newPortStringList.clear();
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
        newPortStringList += info.portName();

    if(newPortStringList.size() != portStringList.size())
    {
        portStringList = newPortStringList;
        ui->comboBox->clear();
        ui->comboBox->addItems(portStringList);
    }
}

//打开串口
void Widget::on_pushButton_clicked()
{
    if(ui->pushButton->text() == QString("打开串口"))
    {
        serial->setPortName(ui->comboBox->currentText());
        serial->setBaudRate(ui->comboBox_2->currentText().toInt());

        switch(ui->comboBox_3->currentText().toInt())
        {
            case 5:serial->setDataBits(QSerialPort::Data5);break;
            case 6:serial->setDataBits(QSerialPort::Data6);break;
            case 7:serial->setDataBits(QSerialPort::Data7);break;
            case 8:serial->setDataBits(QSerialPort::Data8);break;
            default:serial->setDataBits(QSerialPort::UnknownDataBits);
        }

        switch(ui->comboBox_4->currentIndex())
        {
            case 0:serial->setParity(QSerialPort::EvenParity);break;
            case 1:serial->setParity(QSerialPort::OddParity);break;
            case 2:serial->setParity(QSerialPort::NoParity);break;
            default:serial->setParity(QSerialPort::UnknownParity);
        }

        switch(ui->comboBox_5->currentIndex())
        {
            case 0:serial->setStopBits(QSerialPort::OneStop);break;
            case 1:serial->setStopBits(QSerialPort::OneAndHalfStop);break;
            case 2:serial->setStopBits(QSerialPort::TwoStop);break;
            default:serial->setStopBits(QSerialPort::UnknownStopBits);
        }

        serial->setFlowControl(QSerialPort::NoFlowControl);

        if(!serial->open(QIODevice::ReadWrite))
        {
            QMessageBox::information(this, "错误提示", "无法打开串口", QMessageBox::Ok);
            return;
        }
        ui->comboBox->setEnabled(false);
        ui->comboBox_2->setEnabled(false);
        ui->comboBox_3->setEnabled(false);
        ui->comboBox_4->setEnabled(false);
        ui->comboBox_5->setEnabled(false);

        ui->pushButton->setText("关闭串口");
    }
    else
    {
        serial->close();
        ui->comboBox->setEnabled(true);
        ui->comboBox_2->setEnabled(true);
        ui->comboBox_3->setEnabled(true);
        ui->comboBox_4->setEnabled(true);
        ui->comboBox_5->setEnabled(true);

        ui->pushButton->setText("打开串口");
    }
}
//获取串口中的数据
void Widget::serialPort_readyRead()
{
    QString last_text;
    int length;
    int i;
    if(ui->checkBox_3->checkState() != Qt::Checked)
    {
        last_text = ui->textEdit->toPlainText();
        Receivetext = serial->readAll();
        Receive_Byte += Receivetext.length();
        ui->label_9->setText(QString::number(Receive_Byte));

        if(ui->checkBox_2->checkState() == Qt::Checked)  //hex
        {
            Receivetext = Receivetext.toLatin1().toHex();
            length = Receivetext.length();
            for(i = 0; i <= length/2; i++)
            {
                Receivetext.insert(2+3*i, ' ');
            }
        }
        else  //ASCII
        {
            Receivetext = Receivetext.toLatin1();
        }
        last_text = last_text.append(Receivetext);
        ui->textEdit->setText(last_text);

    }
}

void Widget::on_checkBox_clicked()
{
    ui->checkBox->setCheckState(Qt::Checked);
    ui->checkBox_2->setCheckState(Qt::Unchecked);
    ui->checkBox_3->setCheckState(Qt::Unchecked);
}

void Widget::on_checkBox_2_clicked()
{
    ui->checkBox->setCheckState(Qt::Unchecked);
    ui->checkBox_2->setCheckState(Qt::Checked);
    ui->checkBox_3->setCheckState(Qt::Unchecked);
}

void Widget::on_checkBox_3_clicked()
{
    ui->checkBox->setCheckState(Qt::Unchecked);
    ui->checkBox_2->setCheckState(Qt::Unchecked);
    ui->checkBox_3->setCheckState(Qt::Checked);
}
//发送数据
void Widget::on_pushButton_2_clicked()
{
    QByteArray bytearray;

    Sendtext = ui->textEdit_2->toPlainText();
    bytearray = Sendtext.toLatin1();
    serial->write(bytearray);
    Send_Byte += Sendtext.length();
    ui->label_11->setText(QString::number(Send_Byte));
}

void Widget::on_pushButton_3_clicked()
{
    ui->textEdit->clear();
}

void Widget::on_pushButton_4_clicked()
{
    ui->textEdit_2->clear();
}

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值