QT有自带的串口类,所以使用串口很便捷
环境:QT5.9.0+Creator4.3.1,WIN10
1、添加代码
.pro
QT += serialport
.h头文件:
#ifndef QMYSERIALPORT_H
#define QMYSERIALPORT_H
#include <QMainWindow>
#include <QSerialPort> //提供访问串口的功能
#include <QSerialPortInfo> //提供系统中存在的串口的信息
#include <QLabel>
#include <QAction>
#include <QComboBox>
#include <QSpinBox>
#include <QFontComboBox>
#include <QToolButton>
#include <QStatusBar>
#include <QTextCharFormat>
#include <QDockWidget>
#include <QStackedWidget>
#include <QPushButton>
#include <QVBoxLayout>
#include <QButtonGroup>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsEllipseItem>
#include <QLineEdit>
#include <QLayout>
#include <QTableWidget>
#include <QTextEdit>
namespace Ui
{
class QMySerialPort;
}
class QMySerialPort : public QMainWindow
{
Q_OBJECT
public:
explicit QMySerialPort(QWidget *parent = 0);
~QMySerialPort();
void bluetooth();
void statusOfAll();
private:
//基本布局
QGraphicsScene *scene;
//停靠窗口1,显示蓝牙连接状态
QLabel *BlueToothLabel;
QComboBox *BlueToothPortComboBox;
QPushButton *ConnectBtn;
QPushButton *BreakBtn;
QPushButton *SendBtn;
QSerialPort *CurrentPort;
QLabel *BaudRateLabel;
QComboBox *BaudRateComBox;
QLabel *DateRateLabel;
QComboBox *DateRateComBox;
QLabel *ParityLabel;
QComboBox *ParityComBox;
QLabel *StopBitsLabel;
QComboBox *StopBitsComBox;
//停靠窗口3,3个显示窗口,状态/接受/发送
QTextEdit *StatusOfDock3;
QTextEdit *SendInfo;
QTextEdit *ReceiveInfo;
private slots:
void on_clearButton_clicked();
void on_sendButtton_clicked();
void on_connectButton_clicked();
void on_breakButton_clicked();
void Read_Data();
private:
Ui::QMySerialPort *ui;
};
#endif // QMYSERIALPORT_H
.cpp
#include "qmyserialport.h"
#include "ui_qmyserialport.h"
QMySerialPort::QMySerialPort(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::QMySerialPort)
{
ui->setupUi(this);
setWindowTitle(tr("串口通信"));
resize(1000,500);
bluetooth();
statusOfAll();
}
QMySerialPort::~QMySerialPort()
{
delete ui;
}
void QMySerialPort::bluetooth()//蓝牙模块
{
QDockWidget *dock1 = new QDockWidget(tr("DockWindow1"));
dock1->setFeatures(QDockWidget::DockWidgetMovable|QDockWidget::DockWidgetFloatable); //窗口可移动
dock1->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
addDockWidget(Qt::RightDockWidgetArea,dock1);
dock1->setStyleSheet("QPushButton{color:white;background-color:black}");//按钮样式设置
BlueToothLabel = new QLabel(tr("Port name: "));
ConnectBtn = new QPushButton("Connect");
BreakBtn = new QPushButton(tr("Break"));
SendBtn = new QPushButton(tr("Send"));
BlueToothPortComboBox = new QComboBox;
BaudRateLabel = new QLabel(tr("BaudRate: "));
BaudRateComBox = new QComboBox;
BaudRateComBox->addItem(tr("9600"));
BaudRateComBox->addItem(tr("19200"));
BaudRateComBox->addItem(tr("38400"));
BaudRateComBox->addItem(tr("57600"));
BaudRateComBox->addItem(tr("11520"));
BaudRateComBox->setCurrentIndex(0);//设置下拉选择默认为第4个
DateRateLabel = new QLabel(tr("DateRate: "));
DateRateComBox = new QComboBox;
DateRateComBox->addItem("5");
DateRateComBox->addItem("6");
DateRateComBox->addItem("7");
DateRateComBox->addItem("8");
DateRateComBox->setCurrentIndex(3);//设置下拉选择默认为第4个
ParityLabel = new QLabel("Parity");
ParityComBox = new QComboBox;
ParityComBox->addItem("On");
ParityComBox->addItem("Off");
ParityComBox->setCurrentIndex(1);
StopBitsLabel = new QLabel("StopBits: ");
StopBitsComBox = new QComboBox;
StopBitsComBox->addItem("1");
StopBitsComBox->addItem("2");
//进行布局,先横向再纵向
QHBoxLayout *Dock1Layout1 = new QHBoxLayout();
Dock1Layout1->addWidget(BlueToothLabel);
Dock1Layout1->addWidget(BlueToothPortComboBox);
QHBoxLayout *Dock1Layout2 = new QHBoxLayout();
Dock1Layout2->addWidget(BaudRateLabel);
Dock1Layout2->addWidget(BaudRateComBox);
QHBoxLayout *Dock1Layout3 = new QHBoxLayout();
Dock1Layout3->addWidget(DateRateLabel);
Dock1Layout3->addWidget(DateRateComBox);
QHBoxLayout *Dock1Layout4 = new QHBoxLayout();
Dock1Layout4->addWidget(ParityLabel);
Dock1Layout4->addWidget(ParityComBox);
QHBoxLayout *Dock1Layout5 = new QHBoxLayout();
Dock1Layout5->addWidget(StopBitsLabel);
Dock1Layout5->addWidget(StopBitsComBox);
QHBoxLayout *Dock1Layout6 = new QHBoxLayout();
Dock1Layout6->addWidget(ConnectBtn);//点击后就开始寻找设备进行连接
Dock1Layout6->addWidget(BreakBtn);//点击后断开串口连接
Dock1Layout6->addWidget(SendBtn);
QVBoxLayout *Dock1Layout = new QVBoxLayout();
Dock1Layout->setAlignment(Qt::AlignCenter);
Dock1Layout->addLayout(Dock1Layout1);
Dock1Layout->addLayout(Dock1Layout2);
Dock1Layout->addLayout(Dock1Layout3);
Dock1Layout->addLayout(Dock1Layout4);
Dock1Layout->addLayout(Dock1Layout5);
Dock1Layout->addLayout(Dock1Layout6);
QWidget *Dock1Widget = new QWidget();
Dock1Widget->setLayout(Dock1Layout);
dock1->setWidget(Dock1Widget);
ConnectBtn->setMinimumWidth(70);
BreakBtn->setMaximumWidth(50);
//搜索串口,并添加到选项上供使用者选择
foreach(const QSerialPortInfo &Info,QSerialPortInfo ::availablePorts())
{
QSerialPort CurrentPort;
CurrentPort.setPort(Info);
if(CurrentPort.open(QIODevice::ReadWrite))
{
BlueToothPortComboBox->addItem(CurrentPort.portName());//插入串口的名字
CurrentPort.close(); //先开再关,把串口名称先导入
}
}
connect(ConnectBtn, SIGNAL(clicked()),this,SLOT(on_connectButton_clicked()));
connect(BreakBtn, SIGNAL(clicked()),this,SLOT(on_breakButton_clicked()));
connect(SendBtn,SIGNAL(clicked()),this,SLOT(on_sendButtton_clicked()));
}
void QMySerialPort::on_clearButton_clicked()//清空发送与接收窗口信息
{
SendInfo->clear();
ReceiveInfo->clear();
}
//发送数据
void QMySerialPort::on_sendButtton_clicked()
{
QByteArray SendBytes = SendInfo->toPlainText().toLatin1();//toPlainText(将文本编辑的文本转换为纯文本)
if(SendBytes.isEmpty())//判断发送数据是否为空
{
StatusOfDock3->append("No message can be sent, Please write something");
}
CurrentPort->write(SendBytes);
}
//读取接收到的数据
void QMySerialPort::Read_Data()
{
QByteArray buf;
buf = CurrentPort->readAll();//Qbytearray类提供一个字节数组,buf这里应该是缓冲数据的功能
if(!buf.isEmpty())
{
QString str = this->ReceiveInfo->toPlainText().toUtf8();
str += tr(buf);
ReceiveInfo->clear();
ReceiveInfo->append(str);
}
buf.clear();
}
//联机
void QMySerialPort::on_connectButton_clicked()
{
CurrentPort = new QSerialPort;
CurrentPort->setPortName(BlueToothPortComboBox->currentText());//设置串口名
//设置波特率
switch (BaudRateComBox->currentIndex())
{
case 0: StatusOfDock3->append("Baud:9600");
CurrentPort->setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections); break;
case 1: StatusOfDock3->append("Baud:19200");
CurrentPort->setBaudRate(QSerialPort::Baud19200,QSerialPort::AllDirections); break;
case 2: StatusOfDock3->append("Baud:38400");
CurrentPort->setBaudRate(QSerialPort::Baud38400,QSerialPort::AllDirections); break;
case 3: StatusOfDock3->append("Baud:57600");
CurrentPort->setBaudRate(QSerialPort::Baud57600,QSerialPort::AllDirections); break;
case 4: StatusOfDock3->append("Baud:115200");
CurrentPort->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections); break;
default: break;
}
//设置数据位数
switch(DateRateComBox->currentIndex())
{
case 0: StatusOfDock3->append("Data:5");
CurrentPort->setDataBits(QSerialPort::Data5); break;
case 1: StatusOfDock3->append("Data:6");
CurrentPort->setDataBits(QSerialPort::Data6); break;
case 2: StatusOfDock3->append("Data:7");
CurrentPort->setDataBits(QSerialPort::Data7); break;
case 3: StatusOfDock3->append("Data:8");
CurrentPort->setDataBits(QSerialPort::Data8); break;
default: break;
}
//设置奇偶校验
switch(ParityComBox->currentIndex())
{
case 1:StatusOfDock3->append("Parity: off");
CurrentPort->setParity(QSerialPort::NoParity); break;
default: break;
}
switch(StopBitsComBox->currentIndex()) //设置停止位
{
case 0: StatusOfDock3->append("StopBits:1");
CurrentPort->setStopBits(QSerialPort::OneStop); break;
case 1: StatusOfDock3->append("StopBits:2");
CurrentPort->setStopBits(QSerialPort::TwoStop); break;
default: break;
}
CurrentPort->setFlowControl(QSerialPort::NoFlowControl); //设置流控制
CurrentPort->open(QIODevice::ReadWrite);//打开串口
if(CurrentPort->isOpen())
{
StatusOfDock3->append("Succeesfully open the Port ");
//关闭设置菜单使能
BlueToothPortComboBox->setEnabled(false);
BaudRateComBox->setEnabled(false);
DateRateComBox->setEnabled(false);
ParityComBox->setEnabled(false);
StopBitsComBox->setEnabled(false);
ConnectBtn->setEnabled(false);
BreakBtn->setEnabled(true);
SendBtn->setEnabled(true);
}
else
{
StatusOfDock3->append("Defeatly open the port");
}
//连接信号槽
QObject::connect(CurrentPort, &QSerialPort::readyRead, this, &QMySerialPort::Read_Data);
}
//断开
void QMySerialPort::on_breakButton_clicked()
{
//关闭串口
CurrentPort->clear();
CurrentPort->close();
CurrentPort->deleteLater();
StatusOfDock3->append("Serial connection has been disconnected");
//恢复设置使能
BlueToothPortComboBox->setEnabled(true);
BaudRateComBox->setEnabled(true);
DateRateComBox->setEnabled(true);
ParityComBox->setEnabled(true);
StopBitsComBox->setEnabled(true);
ConnectBtn->setEnabled(true);
BreakBtn->setEnabled(false);
SendBtn->setEnabled(false);
}
void QMySerialPort::statusOfAll()//最下面的窗口,显示图像的各个数据;暂时让收发数据显示在这里,到后面可隐藏掉
{
//停靠窗口3,显示图像各种参数
QDockWidget *dock3 = new QDockWidget(tr("DockWindow3"));
dock3->setFeatures(QDockWidget::DockWidgetMovable|QDockWidget::DockWidgetFloatable); //窗口可移动
dock3->setAllowedAreas(Qt::BottomDockWidgetArea);
addDockWidget(Qt::BottomDockWidgetArea,dock3);
dock3->setMinimumSize(1500,100);
QHBoxLayout *Dock3Layout = new QHBoxLayout;
StatusOfDock3 = new QTextEdit;
StatusOfDock3->setMinimumSize(300,200);
SendInfo = new QTextEdit;
ReceiveInfo = new QTextEdit;
Dock3Layout->addWidget(StatusOfDock3);
Dock3Layout->addWidget(SendInfo);
Dock3Layout->addWidget(ReceiveInfo);
QWidget *Dock3Widget = new QWidget();
Dock3Widget->setLayout(Dock3Layout);
dock3->setWidget(Dock3Widget);
}
2、准备一个虚拟串口的功能和串口助手
先使用虚拟串口将COM1和COM2关联起来
然后将串口助手和生成的软件断开、波特率、等等都设置好
源码中有接受和发送函数,使用时自行修改代码就可以了