QT 串口通信笔记

一,头文件

       #include <QSerialPort>           //提供访问串口的功能

       #include <QSerialPortInfo>    //提供系统中存在的串口的信息

二,搜索串口

 //搜索串口,并添加到选项上供使用者选择
    foreach(const QSerialPortInfo &Info,QSerialPortInfo ::availablePorts())
    {
        QSerialPort CurrentPort;
        CurrentPort.setPort(Info);
        if(CurrentPort.open(QIODevice::ReadWrite))
        {
          ui->comboBox_port->addItem(CurrentPort.portName());//插入串口的名字
          CurrentPort.close();   //先开再关,把串口名称先导入
        }

    }

三,连接串口

 CurrentUart->open(QIODevice::ReadWrite);

四,读串口数据

QByteArry ReadBuf = CurrentUart->readAll();

if(!ReadBuf.isEmpty())
{
    str += tr(ReadBuf);//???
    ui->plainTextEdit->appendPlainText(str);
}

ReadBuf.clear();

 

五,写数据

 QByteArray ArraySend = ui->plainTextEdit_2->toPlainText().toLatin1();
 CurrentUart->write(QByteArray::fromHex(ArraySend));

六,关掉串口

CurrentUart->clear();
CurrentUart->close();

七,源代码

#ifndef UARTDISPLAY_H
#define UARTDISPLAY_H
#include <QSerialPort>           //提供访问串口的功能
#include <QSerialPortInfo>    //提供系统中存在的串口的信息
#include <QWidget>
#include <QTimer>
#include <QTextEdit>
#include <QtDebug>
#include "linklist.h"
#include "datahandle.h"

extern uint8_t SerialStatus;

namespace Ui {
class Uartdisplay;
}

class Uartdisplay : public QWidget
{
    Q_OBJECT

public:
    explicit Uartdisplay(QWidget *parent = nullptr);
    ~Uartdisplay();
    void uint8_to_charHex(uint8_t *data,uint16_t len,uint8_t *retbuf);
    void QString_to_charHex(QString *data,uint16_t len,QString *retbuf);
    void QByteArray_to_uint8hex(QByteArray *data,uint8_t *hexdata,uint16_t len);

private slots:
    void on_pushButton_clicked();
    void Read_Data();

    void on_pushButton_2_clicked();

    void on_pushButton_3_clicked();

    void on_pushButton_4_clicked();

    void on_pushButton_5_clicked();

private:
    Ui::Uartdisplay *ui;
     QSerialPort *CurrentUart = new QSerialPort();
     QTimer *TimerRead = new QTimer();
     QByteArray ReadBuf;
     QTextEdit *ReceiveInfo;
};

#endif // UARTDISPLAY_H
#include "uartdisplay.h"
#include "ui_uartdisplay.h"

#include <QSerialPort>           //提供访问串口的功能
#include <QSerialPortInfo>    //提供系统中存在的串口的信息
#include <QFileDialog>
#include <QDateTime>
#include <QMessageBox>


uint8_t SerialStatus = 0;
extern Linklist link;


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

    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);

    ui->checkBox->setCheckState(Qt::CheckState::Checked);//CheckBox默认状态
    ui->checkBox_2->setCheckState(Qt::CheckState::Checked);//CheckBox默认状态

    ui->comboBox_baudrate->addItem("9600");
    ui->comboBox_baudrate->addItem("19200");
    ui->comboBox_baudrate->addItem("38400");
    ui->comboBox_baudrate->addItem("57600");
    ui->comboBox_baudrate->addItem("115200");
    ui->comboBox_baudrate->setCurrentIndex(4);

    ui->comboBox_datarate->addItem("5");
    ui->comboBox_datarate->addItem("6");
    ui->comboBox_datarate->addItem("7");
    ui->comboBox_datarate->addItem("8");
    ui->comboBox_datarate->setCurrentIndex(3);

    ui->comboBox_parity->addItem("On");
    ui->comboBox_parity->addItem("Off");
    ui->comboBox_parity->setCurrentIndex(1);

    ui->comboBox_stopbit->addItem("1");
    ui->comboBox_stopbit->addItem("2");
    ui->comboBox_stopbit->setCurrentIndex(0);

    //搜索串口,并添加到选项上供使用者选择
    foreach(const QSerialPortInfo &Info,QSerialPortInfo ::availablePorts())
    {
        QSerialPort CurrentPort;
        CurrentPort.setPort(Info);
        if(CurrentPort.open(QIODevice::ReadWrite))
        {
          ui->comboBox_port->addItem(CurrentPort.portName());//插入串口的名字
          CurrentPort.close();   //先开再关,把串口名称先导入
        }

    }

     connect(TimerRead,SIGNAL(timeout()),this,SLOT(Read_Data()));

}

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


/*串口读数据*/
void Uartdisplay::Read_Data()
{
    //uint8_t revbuf[255];
    uint8_t TatolLen = 0,CRC = 0;
    uchar *revbuf;
    QString str;
    QDateTime CurrDate = QDateTime::currentDateTime();
    QString CurrDateTime = CurrDate.toString("[hh:mm:ss:zzz]");
    str += CurrDateTime+"收-> ";


    ReadBuf = CurrentUart->readAll();

    if(!ReadBuf.isEmpty())
    {
        if(ui->checkBox->checkState()) //HEX显示
        {
            QString str2 = QString::fromUtf8(ReadBuf.toHex());
            qDebug()<<"lenght : "<<str2.length();
            QString str3;
            QString_to_charHex(&str2,str2.length(),&str3);

            str+=str3;
            ui->plainTextEdit->appendPlainText(str);
            revbuf = (uchar*)ReadBuf.data();

            if(revbuf[0]==0xff)
            {
                TatolLen = ReadBuf.length();
                CRC = datahandle.crc_u8(revbuf,TatolLen-2);
                if(revbuf[TatolLen-1] == 0xff )//&&CRC == revbuf[TatolLen-2])
                {
                    qDebug()<<"recive data ok!!!";
                    memcpy(RevData.data,revbuf,TatolLen);
                    RevData.dataLen = TatolLen;

                    if(revbuf[2] == 0x04)
                    {
                        qDebug()<<"recive data bat!!!";
                        qDebug("recive data ok:%x ,%x ,%x ,%x,%x ,%x ,%x ,%x,%d",RevData.data[0],RevData.data[1],RevData.data[2],RevData.data[3],RevData.data[4],RevData.data[5],RevData.data[6],RevData.data[7],TatolLen);
                        link.insert(link.RevBatList,&RevData);
                    }
                    else
                    {
                        link.insert(link.RevmainwidgetList,&RevData);
                    }
                }
            }
        }
        else
        {
            str += tr(ReadBuf);//???
            ui->plainTextEdit->appendPlainText(str);
        }
    }
    ReadBuf.clear();

    if(!link.list_is_empty(link.SendList))
    {
        uint8_t retbuf[1000];
        QString str;
        QDateTime CurrDate = QDateTime::currentDateTime();
        QString CurrDateTime = CurrDate.toString("[hh:mm:ss:zzz]");
        str += CurrDateTime+"发-> ";
        uint8_to_charHex(link.SendList->next->data.data,link.SendList->next->data.dataLen,retbuf);
        str+= QString(QByteArray((char*)retbuf,(link.SendList->next->data.dataLen)*3));
        ui->plainTextEdit->appendPlainText(str);

        QByteArray ArraySend = QByteArray::fromRawData((char*)link.SendList->next->data.data,link.SendList->next->data.dataLen); //char 转成QByteArray

        CurrentUart->write(ArraySend);

        link.delete_node(&link.SendList);
    }

}

/*连接*/
void Uartdisplay::on_pushButton_clicked()
{
    QString tr;
    CurrentUart->setPortName(ui->comboBox_port->currentText());
    tr+="PortName : "+ui->comboBox_port->currentText()+"  \r\n";
    switch(ui->comboBox_baudrate->currentIndex())
    {
        case 0:
            CurrentUart->setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections);
            tr+="Baud : 9600  \r\n";
            break;
        case 1:
            CurrentUart->setBaudRate(QSerialPort::Baud19200,QSerialPort::AllDirections);
            tr+="Baud : 19200  \r\n";
            break;
        case 2:
            CurrentUart->setBaudRate(QSerialPort::Baud38400,QSerialPort::AllDirections);
            tr+="Baud : 38400  \r\n";
            break;
        case 3:
            CurrentUart->setBaudRate(QSerialPort::Baud57600,QSerialPort::AllDirections);
            tr+="Baud : 57600  \r\n";
            break;
        case 4:
            CurrentUart->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);
            tr+="Baud : 115200  \r\n";
            break;
        default:
            break;
    }

    switch(ui->comboBox_datarate->currentIndex())
    {
        case 0:
            CurrentUart->setDataBits(QSerialPort::Data5);
            tr+="DataBits : 5  \r\n";
            break;
        case 1:
            CurrentUart->setDataBits(QSerialPort::Data6);
            tr+="DataBits : 6  \r\n";
            break;
        case 2:
            CurrentUart->setDataBits(QSerialPort::Data7);
            tr+="DataBits : 7  \r\n";
            break;
        case 3:
            CurrentUart->setDataBits(QSerialPort::Data8);
            tr+="DataBits : 8  \r\n";
            break;
        default:
            break;
    }

    switch(ui->comboBox_parity->currentIndex())
    {
        case 0:
            CurrentUart->setParity(QSerialPort::MarkParity);
            tr+="Parity : On  \r\n";
            break;
        case 1:
            CurrentUart->setParity(QSerialPort::NoParity);
            tr+="Parity : Off  \r\n";
            break;
        default:
            break;
    }


    switch(ui->comboBox_stopbit->currentIndex())
    {
        case 0:
            CurrentUart->setStopBits(QSerialPort::OneStop);
            tr+="StopBits : OneStop  \r\n";
            break;
        case 1:
            CurrentUart->setStopBits(QSerialPort::TwoStop);
            tr+="StopBits : TwoStop  \r\n";
            break;
        default:
            break;
    }

    CurrentUart->setFlowControl(QSerialPort::NoFlowControl);
    CurrentUart->open(QIODevice::ReadWrite);

    if(CurrentUart->isOpen())
    {
        ui->comboBox_port->setEnabled(false);
        ui->comboBox_baudrate->setEnabled(false);
        ui->comboBox_datarate->setEnabled(false);
        ui->comboBox_parity->setEnabled(false);
        ui->comboBox_stopbit->setEnabled(false);

        ui->pushButton->setEnabled(false);
        ui->pushButton_2->setEnabled(true);

        tr+="\r\n\r\nconnect uart successfull!!!\r\n\r\n";

        ui->plainTextEdit->setPlainText(tr);
        SerialStatus = 1;
    }
    else
    {
        ui->plainTextEdit->setPlainText("connect uart fail!!!");
    }

    TimerRead->start(500);
}

/*断开连接*/
void Uartdisplay::on_pushButton_2_clicked()
{
    CurrentUart->clear();
    CurrentUart->close();
    //CurrentUart->deleteLater();

    ui->comboBox_port->setEnabled(true);
    ui->comboBox_baudrate->setEnabled(true);
    ui->comboBox_datarate->setEnabled(true);
    ui->comboBox_parity->setEnabled(true);
    ui->comboBox_stopbit->setEnabled(true);

    ui->pushButton->setEnabled(true);
    ui->pushButton_2->setEnabled(false);
    TimerRead->stop();
}

/*清楚窗口*/
void Uartdisplay::on_pushButton_3_clicked()
{
    ui->plainTextEdit->clear();
}

/*发送数据*/
void Uartdisplay::on_pushButton_4_clicked()
{
    QString str,str1,str2;
    QDateTime CurrDate = QDateTime::currentDateTime();
    QString CurrDateTime = CurrDate.toString("[hh:mm:ss:zzz]");
    str += CurrDateTime+"发-> ";
    str1 = ui->plainTextEdit_2->toPlainText();
    qDebug()<<"str1:"<<str1;
    if(ui->checkBox_2->checkState()) //HEX显示
    {
        QString_to_charHex(&str1,str1.length(),&str2);
        qDebug()<<"str2:"<<str2;
        str+= str2;

        ui->plainTextEdit->appendPlainText(str);
        QByteArray ArraySend = ui->plainTextEdit_2->toPlainText().toLatin1();
        CurrentUart->write(QByteArray::fromHex(ArraySend));
    }
    else
    {
        str+= str1;

        ui->plainTextEdit->appendPlainText(str);
        QByteArray ArraySend = ui->plainTextEdit_2->toPlainText().toLatin1();
        CurrentUart->write(ArraySend);
    }
}

void Uartdisplay::uint8_to_charHex(uint8_t *data,uint16_t len,uint8_t *retbuf)
{
    for(uint8_t i=0;i<len;i++)
    {
        if(((data[i]&0xf0)>>4)<=9)
        {
            retbuf[i*3] = ((data[i]&0xf0)>>4)+'0';
        }
        else
        {
            retbuf[i*3] = ((data[i]&0xf0)>>4)+87;
        }

        if((data[i]&0x0f)<=9)
        {
            retbuf[i*3+1] = (data[i]&0x0f)+'0';
        }
        else
        {
            retbuf[i*3+1] = (data[i]&0x0f)+87;
        }

        retbuf[i*3+2] = ' ';
    }
}


void Uartdisplay::QString_to_charHex(QString *data,uint16_t len,QString *retbuf)
{
    uint16_t j = 0;
    for(uint16_t i=0;i<len;i++)
    {
        (*retbuf)[i+j] = (*data)[i];

        if(i%2==1)
        {
            j+=1;
            (*retbuf)[i+j] = ' ';
        }

    }
}

void Uartdisplay::QByteArray_to_uint8hex(QByteArray *data,uint8_t *hexdata,uint16_t len)
{
    uint8_t Tempdata = 0;
    for(uint16_t i = 0;i<len;i++)
    {
        if(data->data()[i]=='\0')
        {
            return;
        }

        Tempdata = Tempdata*0x10+(data->data()[i]-'0');

        if(i%2==1)
        {
            hexdata[i/2] = Tempdata;
            Tempdata = 0;
        }
    }
}

void Uartdisplay::on_pushButton_5_clicked()
{
    QString tragetpath =QFileDialog::getExistingDirectory(this, "选择存储目录","//",QFileDialog::ShowDirsOnly| QFileDialog::DontResolveSymlinks);
    //tragetpath.replace("\\","//");
    tragetpath.replace("/","//");
    QString text = ui->plainTextEdit->toPlainText();
    qDebug()<<tragetpath;
    QFile file(tragetpath+"//Uart_Log.txt");

    if(!file.open(QIODevice::Append|QIODevice::Text))  //append追加,不会覆盖之前的文件
    {
        QMessageBox::critical(this,"错误","文件打开失败,信息没有保存!","确定");
        return;
    }

    QTextStream in(&file);//写入
    in<<text;
    file.close();
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页