主要步骤为四条函数语句:
第一步:连接串口:在此之前设置波特率、停止位、校验位、端口号最后调用此函数
my_serialPort->open(QIODevice::ReadWrite)
第二步:发送报文:在此之前设置号sendByte的字节数据格式,然后调用此函数发送出去
my_serialPort->write(sendByte);
第三步:接收报文:my_serialPort->readAll()是被QSerialPort::readyRead触发
connect(my_serialPort,&QSerialPort::readyRead,
[=]()
{
my_serialPort->readAll();
}
);
具体实现方法如下:
准备阶段:
QT += core gui serialport
#include<QSerialPort>
#include<QSerialPortInfo>
#include <QDebug>
#include<QDateTime>
#include<QByteArray>
#include<QTextCodec>
//手动更新端口号到下拉框
connect(ui->button_newProt,&QPushButton::clicked,this,&Widget::comboBox_newPort);
//读取端口号到下拉框
void Widget::comboBox_newPort()
{
//先清除下拉框端口号数据
ui->CB_port->clear();
//重读端口号到下拉框
foreach(QSerialPortInfo serialPort,QSerialPortInfo::availablePorts())
{
ui->CB_port->addItem(serialPort.portName());
}
qDebug("Widget完成串口读写");
}
第一步:按钮连接串口
//手动按钮连接串口
connect(ui->button_connectPort,&QPushButton::clicked,this,&Widget::connection_Prot);
连接串口的槽函数编写
//实例化串口
QSerialPort *my_serialPort=new QSerialPort();
//连接串口
void Widget::connection_Prot()
{
//实例化串口
//如果串口打开,则关闭
if(my_serialPort->isOpen())
{
my_serialPort->clear();
my_serialPort->close();
}
//设置串口
my_serialPort->setPortName(ui->CB_port->currentText());
//波特率
my_serialPort->setBaudRate(QSerialPort::Baud38400,QSerialPort::AllDirections);
//数据位
my_serialPort->setDataBits(QSerialPort::Data8);
//校验位偶
my_serialPort->setParity(QSerialPort::EvenParity);
//停止位1
my_serialPort->setStopBits(QSerialPort::OneStop);
my_serialPort->setFlowControl(QSerialPort::NoFlowControl);
//尝试能否打开此串口
if(my_serialPort->open(QIODevice::ReadWrite))
{
info_text("串口连接成功");
}
else
{
info_text("串口连接失败");
return;
}
}
第二步:发送报文
//手动按钮发送数据
connect(ui->button_send,&QPushButton::clicked,this,&Widget::send_command);
发送报文槽函数的编写
//发送命令
void Widget::send_command()
{
QByteArray sendByte;
sendByte.resize(8);
sendByte[0]=0X01;
sendByte[1]=0X05;
sendByte[2]=0X02;
sendByte[3]=0X0A;
sendByte[4]=0XFF;
sendByte[5]=0X00;
sendByte[6]=0XAD;
sendByte[7]=0X80;
//sendByte.
qint64 ref;
ref = my_serialPort->write(sendByte);
//把反馈回来的ref转化为string
QString B=tr("%1").arg(ref);
info_text("已成功发送"+B+"个字节");
info_text("发送数据为:"+Delimited_Arrary(sendByte.toHex()));
}
//显示数据
void Widget::info_text(QString str)
{
ui->textBrowser->append(time.currentDateTime().toString("yyyy-MM-dd::hh:mm:ss ")+str);
}
第三步:接收报文
//接受反馈数据
connect(my_serialPort,&QSerialPort::readyRead,this,&Widget::read_info);
接收报文的槽函数
//读取反馈回来的数据
void Widget::read_info()
{
QByteArray ba;
ba.resize(1024);
ba=my_serialPort->readAll();
//ba.toHex()这一步很关键,没有这一步显示的是乱码
info_text("接受数据为:"+Delimited_Arrary(ba.toHex()));
}
//把字节数组转化为字符串并且有空格隔开
QString Widget::Delimited_Arrary(QByteArray ba)
{
QString ba_str;
for (int i=0;i<ba.size();i++ )
{
ba_str+=ba[i];
ba_str+=ba[++i];
ba_str+=" ";
}
return ba_str;
}
后期将封装此方法以及添加报文xml