serialport.pro
QT += core gui
QT += serialport testlib
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
#CONFIG += console
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
widget.cpp
HEADERS += \
widget.h
FORMS += \
widget.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QTextCodec>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_pushButtonSearch_clicked();
void on_pushButtonOpen_clicked();
void on_pushButtonsend_clicked();
void receiveInfo();
private:
Ui::Widget *ui;
QStringList m_portNameList;
QStringList getPortNameList();
QSerialPort *m_serialPort;
void convertStringToHex(const QString &str, QByteArray &byteData);
char convertCharToHex(char ch);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <iostream>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
m_serialPort = new QSerialPort;
connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
}
Widget::~Widget()
{
delete ui;
}
QStringList Widget::getPortNameList()
{
QStringList m_serialPortName;
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
m_serialPortName << info.portName();
qDebug()<<"serialPortName:"<<info.portName();
}
return m_serialPortName;
}
void Widget::on_pushButtonSearch_clicked()
{
m_portNameList = getPortNameList();
ui->comboBox0->addItems(m_portNameList);
}
void Widget::on_pushButtonOpen_clicked()
{
if (ui->pushButtonOpen->text()=="打开串口")
{
if(m_serialPort->isOpen())
{
m_serialPort->clear();
m_serialPort->close();
}
m_serialPort->setPortName(m_portNameList[ui->comboBox0->currentIndex()]);
if(!m_serialPort->open(QIODevice::ReadWrite))
{
qDebug()<<m_portNameList[ui->comboBox0->currentIndex()]<<"打开失败!";
return;
}
//打开成功
m_serialPort->setBaudRate(ui->comboBox1->currentText().toInt(),QSerialPort::AllDirections);//设置波特率和读写方向
m_serialPort->setDataBits(QSerialPort::Data8); //数据位为8位
m_serialPort->setFlowControl(QSerialPort::NoFlowControl); //无流控制
m_serialPort->setParity(QSerialPort::NoParity); //无校验位
m_serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
ui->pushButtonOpen->setText("关闭串口");
} else
{
m_serialPort->close();
ui->pushButtonOpen->setText("打开串口");
}
}
void Widget::on_pushButtonsend_clicked()
{
QString m_strSendData = ui->lineEditsend->text();
if(ui->pushButtonsend->isChecked())
{
if (m_strSendData.contains(" "))
{
m_strSendData.replace(QString(" "),QString("")); //把空格去掉
}
QByteArray sendBuf;
convertStringToHex(m_strSendData, sendBuf); //把QString 转换 为 hex
m_serialPort->write(sendBuf);
}
else
{
m_serialPort->write(m_strSendData.toLocal8Bit());
}
}
void Widget::convertStringToHex(const QString &str, QByteArray &byteData)
{
int hexdata,lowhexdata;
int hexdatalen = 0;
int len = str.length();
byteData.resize(len/2);
char lstr,hstr;
for(int i=0; i<len; )
{
//char lstr,
hstr=str[i].toLatin1();
if(hstr == ' ')
{
i++;
continue;
}
i++;
if(i >= len)
break;
lstr = str[i].toLatin1();
hexdata = convertCharToHex(hstr);
lowhexdata = convertCharToHex(lstr);
if((hexdata == 16) || (lowhexdata == 16))
break;
else
hexdata = hexdata*16+lowhexdata;
i++;
byteData[hexdatalen] = (char)hexdata;
hexdatalen++;
}
byteData.resize(hexdatalen);
}
//-----------
char Widget::convertCharToHex(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);
}
void Widget::receiveInfo()
{
m_serialPort->waitForReadyRead(50);//阻塞函数
QByteArray info = m_serialPort->readAll();
std::cout<<std::string(info);
QString strReceiveData = "";
if(ui->radioButton1->isChecked())
{
QByteArray hexData = info.toHex();
strReceiveData = hexData.toUpper();
qDebug()<<"接收到串口数据: "<<strReceiveData;
for(int i=0; i<strReceiveData.size(); i+=2+1)
strReceiveData.insert(i, QLatin1String(" "));
strReceiveData.remove(0, 1);
qDebug()<<"处理后的串口数据: "<<strReceiveData;
ui->textEditReceive->append(strReceiveData);
}
else
{
strReceiveData = QString(info);
QTextCodec *tc = QTextCodec::codecForName("GBK");
QString tmpQStr = tc->toUnicode(info);
ui->textEditReceive->append(tmpQStr);
}
ui->textEditReceive->append("\r\n");
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
//w.show();
return a.exec();
}
widget.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="1">
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string>串口设置</string>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="4" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>检验位:</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QComboBox" name="comboBox4"/>
</item>
<item row="0" column="0">
<widget class="QPushButton" name="pushButtonSearch">
<property name="text">
<string>搜索串口</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="pushButtonOpen">
<property name="text">
<string>打开串口</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="comboBox1">
<item>
<property name="text">
<string>9600</string>
</property>
</item>
<item>
<property name="text">
<string>115200</string>
</property>
</item>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="comboBox0"/>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>波特率:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QComboBox" name="comboBox3"/>
</item>
<item row="3" column="1">
<widget class="QComboBox" name="comboBox2"/>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>串口号:</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>数据位:</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QComboBox" name="comboBox5"/>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>停止位:</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="label_6">
<property name="text">
<string>流控:</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>接收设置</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="1" column="1">
<widget class="QCheckBox" name="checkBox1">
<property name="text">
<string>显示发送</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QRadioButton" name="radioButton1">
<property name="text">
<string>Hex</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QRadioButton" name="radioButton0">
<property name="text">
<string>ASCII</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="checkBox0">
<property name="text">
<string>自动换行</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QCheckBox" name="checkBox2">
<property name="text">
<string>显示时间</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="pushButtonSave">
<property name="text">
<string>存入文件</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_2">
<property name="title">
<string>发送设置</string>
</property>
<layout class="QGridLayout" name="gridLayout_4">
<item row="0" column="1">
<widget class="QRadioButton" name="radioButton3">
<property name="text">
<string>Hex</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="spinBox">
<property name="suffix">
<string>ms</string>
</property>
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>1000</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="checkBox3">
<property name="text">
<string>自动重发</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QRadioButton" name="radioButton2">
<property name="text">
<string>ASCII</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButtonsend">
<property name="text">
<string>发送</string>
</property>
</widget>
</item>
</layout>
</item>
<item row="0" column="0">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QGroupBox" name="groupBox_5">
<property name="title">
<string>接收窗口</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QTextEdit" name="textEditReceive"/>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QGroupBox" name="groupBox_4">
<property name="title">
<string>发送窗口</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLineEdit" name="lineEditsend"/>
</item>
</layout>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>