QT第二十六天

使用Qt制作的串口工具

#工程文件加入一下代码
QT       +=serialport
#ifndef WIDGET_H
#define WIDGET_H


#include <QWidget>
#include <QByteArray>
#include <QString>
#include <QCharRef>
#include <QtSerialPort/QSerialPortInfo>
#include <QtSerialPort/QSerialPort>


namespace Ui {
class Widget;
}


class Widget : public QWidget
{
Q_OBJECT




public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private:
    char ConvertHexChar(char ch);
    void StringToHex(QString str, QByteArray &senddata);
private slots:
    void on_OpenSerialButton_clicked();


    void ReadData();
    void on_SendButton_clicked();


private:
    QSerialPort *serial;
Ui::Widget *ui;
};


#endif // WIDGET_H


#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//查找可用串口
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
    QSerialPort serial;
    serial.setPort(info);
    if(serial.open(QIODevice::ReadWrite))
    {
        ui->PortBox->addItem(serial.portName());
        serial.close();
    }
}
//设置波特率下拉菜单默认显示的第0项
ui->PortBox->setCurrentIndex(0);
}


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




void Widget::on_OpenSerialButton_clicked()
{
    if(ui->OpenSerialButton->text()=="打开串口")
    {
        serial=new QSerialPort;
        //
        serial->setPortName(ui->PortBox->currentText());
        //
        serial->open(QIODevice::ReadWrite);
        //
        serial->setBaudRate(ui->BaudBox->currentText().toInt());
        //ui->textEdit_2->setText(ui->BaudBox->currentText());
        //
        switch (ui->BitBox->currentIndex())
        {
        case 0:
            serial->setDataBits(QSerialPort::Data8);break;
        default:
            break;
        }
        //
        switch (ui->ParityBox->currentIndex())
        {
        case 0:
            serial->setParity(QSerialPort::NoParity);break;
        default:
            break;
        }
        serial->setParity(QSerialPort::NoParity);
        //
        switch (ui->StopBox->currentIndex())
        {
        case 0:
            serial->setStopBits(QSerialPort::OneStop);break;
        case 1:
            serial->setStopBits(QSerialPort::TwoStop);break;
        default:
            break;
        }
        //
        serial->setFlowControl(QSerialPort::NoFlowControl);//


        //
        ui->PortBox->setEnabled(false);
        ui->BaudBox->setEnabled(false);
        ui->BitBox->setEnabled(false);
        ui->ParityBox->setEnabled(false);
        ui->StopBox->setEnabled(false);
        ui->OpenSerialButton->setText("关闭串口");
        //
        QObject::connect(serial,&QSerialPort::readyRead,this,&Widget::ReadData);


    }
    else
    {
        //
        serial->clear();
        serial->close();
        serial->deleteLater();
        //
        ui->PortBox->setEnabled(true);
        ui->BaudBox->setEnabled(true);
        ui->BitBox->setEnabled(true);
        ui->ParityBox->setEnabled(true);
        ui->StopBox->setEnabled(true);
        ui->OpenSerialButton->setText("打开串口");


    }
}
void Widget::ReadData()
{
    QByteArray buf;
    buf=serial->readAll().toHex();
    if(!buf.isEmpty())
    {
        QString str;//=ui->textEdit->toPlainText();
        str+=buf;
        str=str.toUpper();
        QString strDis=nullptr;
        for(int i=0;i<str.length();i+=2)
        {
            QString st=str.mid(i,2);
            strDis+=st;
            strDis+=" ";
        }
        ui->textEdit->clear();
        ui->textEdit->append(strDis);
    }
    buf.clear();
}




void Widget::on_SendButton_clicked()
{
    QString str = ui->lineEdit->text();//从LineEdit得到字符串
    int len = str.length();
    if(len%2 == 1)   //如果发送的数据个数为奇数的,则在前面最后落单的字符前添加一个字符0
    {
        str = str.insert(len-1,'0'); //insert(int position, const QString & str)
    }
    QByteArray senddata;


    StringToHex(str,senddata);//将str字符串转换为16进制的形式
    senddata.toHex();


    ui->textEdit_2->setText(senddata);
    serial->write(senddata);//发送到串口


}


char Widget::ConvertHexChar(char ch)


{


    if((ch >= '0') && (ch <= '9'))


        return ch-0x30;


    else if((ch >= 'A') && (ch <= 'F'))


        return ch-'A'+10;


    else if((ch >= 'a') && (ch <= 'f'))


        return ch-32-'A'+10;


    else return (-1);


}










void Widget::StringToHex(QString str, QByteArray &senddata)
{
    int hexdata,lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    senddata.resize(len/2);
    char lstr,hstr;
    for(int i=0; i<len; )
    {
        //char lstr,
        hstr=str[i].toLatin1();
        QString str1;
        //str1.append(hstr);
        //ui->textEdit_2->setText(str1);
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if(i >= len)
            break;
        lstr =str[i].toLatin1();


        //str1.append(lstr);
        //ui->textEdit_2->setText(str1);
        hexdata = ConvertHexChar(hstr);
        //str1.append(hexdata);
        //ui->textEdit_2->setText(str1);
        lowhexdata = ConvertHexChar(lstr);
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else if(hexdata<=7)
        {
            hexdata = hexdata*16+lowhexdata;
        }
        else
        {
            hexdata=hexdata*16+lowhexdata;
        }
        i++;
        senddata[hexdatalen]=(char)hexdata;
        hexdatalen++;
    }
    senddata.resize(hexdatalen);
}




运行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值