基于QT5.13 的串口通信例程

基于QT5.13 的串口通信例程_第1张图片

废话不多说直接上图,   其中包含系统时间获取显示  ;以及网址链接跳转功能

串口开开启以及显示及发送方式基于QT5.13 的串口通信例程_第2张图片;串口号是自动查询基于QT5.13 的串口通信例程_第3张图片。所以选择好波特率就能使用,上图是我与stm8单片机通讯的示例,按照通讯协议单片机按照通讯协议回复。

下面是.h源程序:.h

#ifndef PORT_H
#define PORT_H

#include 
#include 
#include 
QT_BEGIN_NAMESPACE
namespace Ui { class port; }
QT_END_NAMESPACE

class port : public QDialog
{
    Q_OBJECT

public:
    port(QWidget *parent = nullptr);
    ~port();//释放
public:
    bool portconfig(void);

private slots:
    void on_CBoxSerialport_currentIndexChanged(const QString &arg1);
    void on_Btnopen_clicked();

    void on_BtnSend_clicked();
    void on_SerialPort_readyRead();
    void on_pushButton_clicked();
    void time_update();

    void on_BtnCleanRecv_clicked();

    void on_btnweb_clicked();
    QByteArray GetHexValue(QString str);
    char ConvertHexChar(char ch);
    void WriteMyCom();

private:
    Ui::port *ui;
    QSerialPort comport;
    QSerialPort gloabal_port;
    bool mIsOpen;
    QString mpotName;
    QString mbaurate;
    QString mparity;
    QString mdatabits;
    QString mstopbits;
    QLabel *currenTimLabel;


};
#endif // PORT_H

下面是.pp源码:

#include "port.h"
#include "ui_port.h"
#include "QDebug"
#include "QSerialPortInfo"
#include "QList"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
port::port(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::port)
{
    ui->setupUi(this);//布局设置到port中
    mIsOpen = false;
    ui->BtnSend->setEnabled(mIsOpen);
  /*  ui->CBoxSerialport->addItem("COM1");
    ui->CBoxSerialport->addItem("COM2");
    ui->CBoxSerialport->addItem("COM3");
    comport.setPortName("COM4");
    comport.setBaudRate(QSerialPort::Baud38400);
*/
    //自动查找已有串口
    QList serilPortInfo = QSerialPortInfo::availablePorts();
    int count = serilPortInfo.count();
    for (int i = 0;i < count; i++) {
        ui->CBoxSerialport->addItem(serilPortInfo.at(i).portName());
    }
    connect(&comport,&QSerialPort::readyRead,this,&port::on_SerialPort_readyRead); //接收函数触发
    //设置定时器
    QTimer *timer = new QTimer(this);
    timer->start(1000);   //每隔1000ms发送timeout的信号
    connect(timer,SIGNAL(timeout()),this,SLOT(time_update()));

    //获取日期时间并格式化    //可以不用
    QDate::currentDate().toString("yyyy-MM-dd");
    QTime::currentTime().toString("HH:mm:ss");
    QTime::currentTime().toString("HH:mm:ss zzz");
    QDateTime::currentDateTime().toString("yyyy-MM-DD HH:mm:ss");
    QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss:zzz");
   // ui->btnweb->setText("百度");

}
port::~port()
{
    delete ui;
}
//串口初始化
bool port::portconfig()
{
    //获取配置
    mpotName = ui->CBoxSerialport->currentText();
    mbaurate = ui->CBoxBaudrate->currentText();
    mparity = ui->CBoxParity->currentText();
    mdatabits = ui->CBoxDatabits->currentText();
    mstopbits = ui->CBoxStopBits->currentText();
    //设置配置
    comport.setPortName(mpotName);
    if("9600" == mbaurate)
    {
        comport.setBaudRate(QSerialPort::Baud9600);
    }
    if("19200" == mbaurate)
    {
        comport.setBaudRate(QSerialPort::Baud19200);
    }
    if("38400" == mbaurate)
    {
        comport.setBaudRate(QSerialPort::Baud38400);
    }
    if("57600" == mbaurate)
    {
        comport.setBaudRate(QSerialPort::Baud57600);
    }
    if("115200" == mbaurate)
    {
        comport.setBaudRate(QSerialPort::Baud115200);
    }
    if("NONE" == mparity)
    {
        comport.setParity(QSerialPort::NoParity);
    }else if ("ODD" == mparity)
    {
        comport.setParity(QSerialPort::OddParity);
    }
    else
    {
        comport.setParity(QSerialPort::EvenParity);
    }
    if("5" == mdatabits)
    {
        comport.setDataBits(QSerialPort::Data5);
    }else if("6" == mdatabits)
    {
        comport.setDataBits(QSerialPort::Data6);
    }else if("7" == mdatabits)
    {
        comport.setDataBits(QSerialPort::Data7);
    }else
    {
        comport.setDataBits(QSerialPort::Data8);
    }
    if("1.5" == mstopbits)
    {
        comport.setStopBits(QSerialPort::OneAndHalfStop);
    }else if("2" == mstopbits)
    {
        comport.setStopBits(QSerialPort::TwoStop);
    }else
        {
        comport.setStopBits(QSerialPort::OneStop);
    }
    return comport.open(QSerialPort::ReadWrite);
}
//打开串口
void port::on_Btnopen_clicked()
{
    if(true == mIsOpen)
    {
        comport.close();
        ui->Btnopen->setText("打开");
        mIsOpen = false;
        ui->CBoxSerialport->setEnabled(true);
        ui->CBoxBaudrate->setEnabled(true);
        ui->CBoxParity->setEnabled(true);
        ui->CBoxSerialport->setEnabled(true);
        ui->BtnSend->setEnabled(false);
    }else
    {
        if(portconfig() == true)
        {
            mIsOpen = true;
            ui->Btnopen->setText("关闭");
            qDebug()<<"成功打开串口"<CBoxSerialport->setEnabled(false);
            ui->CBoxBaudrate->setEnabled(false);
            ui->CBoxParity->setEnabled(false);
            ui->CBoxSerialport->setEnabled(false);
            ui->BtnSend->setEnabled(true);
        }
    }
}
//获取16进制的值
QByteArray port::GetHexValue(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) break;
        lstr = str[i].toLatin1();
        hexdata = ConvertHexChar(hstr);
        lowhexdata = ConvertHexChar(lstr);
        if((hexdata==16)||(lowhexdata==16))
            break;

        else
            hexdata = hexdata*16+lowhexdata;
            i++;
            senddata[hexdatalen]=(char)hexdata;
            hexdatalen++;
    }
    senddata.resize(hexdatalen);
    return senddata;
}
//数据转换
char port::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-'a'+10;
    else return (-1);
}
//发送函数  发送内容根据选择转成16进制发送  加结束符 以及换行
void port::WriteMyCom()
{
    QString str=ui->textEdit->toPlainText();
    QByteArray outData=str.toLatin1();
    int size = outData.size();
    //QT中的回车只有一个字符\n,而windows下需要解释为\r\n
    if(outData[size-1]!='\n')
    {
        outData.resize(size-1);
        outData[size]='\n';
        outData[size+1]='\n';
    }
    //默认16进制发送的数据没有加入回车符
    if(ui->ckHexSend->isChecked())
    {
        outData=this->GetHexValue(str);
        size=outData.size();
        comport.write(outData);
    }else
    {
        size=outData.size();
        comport.write(outData);
    }
}
//发送
void port::on_BtnSend_clicked()
{
    if(mIsOpen == true)
    {
        this->WriteMyCom();
    }
}
//读取并显示
void port::on_SerialPort_readyRead()
{
    QByteArray recv = comport.readAll();
    if(ui->ckHexRecv->isChecked())
    {                                              // 转成16进制 // 字母大写// 不覆盖的追加显示
       ui->textRecv->insertPlainText(QByteArray(recv.toHex(' ').toUpper().append(' ')));
    }else {
       ui->textRecv->append(QString(recv));
    }
}
//清除发送内容
void port::on_pushButton_clicked()
{
    ui->textEdit->clear();
}
//清除显示内容
void port::on_BtnCleanRecv_clicked()
{
    ui->textRecv->clear();

}
//时间更新函数
void port::time_update()
{
    QString time;
    time=QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    ui->labtime->setText(QString(time));
}
//打开网址连接
void port::on_btnweb_clicked()
{
    QDesktopServices::openUrl(QString("www.baidu.com"));
}
本人小白学习中,不足之处望见怪。

源程序链接:https://download.csdn.net/download/qq_21489487/12408241

本人使用的QT5.13.此处作为备注。以后方便查看。

你可能感兴趣的:(qt,串口调试助手源码,单片机,串口通信)