一、test.pro
添加模块:
QT += serialport
二、mainwindow.h
添加头文件:
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
修改类:
private:
QSerialPort *serial;
private slots:
void ReadData();
void SendData();
void on_pushButton_findcom_clicked();
void on_pushButton_opencom_clicked()
三、mainwindow.cpp
1.查找串口
按钮 pushButton_findcom,下拉菜单 comboBox_com1
void MainWindow::on_pushButton_findcom_clicked(){
foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
QSerialPort serial;
serial.setPort(info);
if(serial.open(QIODevice::ReadWrite)){
ui->comboBox_com1->addItem(serial.portName());
serial.close();
}
}
ui->comboBox_com1->setCurrentIndex(0); //设置波特率下拉菜单默认显示第0项
}
2.打开串口
按钮 pushButton_opencom,text:打开串口
void MainWindow::on_pushButton_opencom_clicked(){
if(ui->pushButton_opencom->text() == tr("打开串口")){
serial = new QSerialPort;
serial->setPortName(ui->comboBox_com1->currentText());
serial->open(QIODevice::ReadWrite);
serial->setBaudRate(QSerialPort::Baud115200);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
ui->pushButton_opencom->setText(tr("关闭串口"));
QObject::connect(serial,SIGNAL(readyRead()),this,SLOT(ReadData()));
}
else{
//关闭串口
serial->clear();
serial->close();
serial->deleteLater();
ui->pushButton_opencom->setText(tr("打开串口"));
}
}
3.读取数据
void MainWindow::ReadData(){
QByteArray byte = serial->readAll();
//校验帧头
if(byte.size()<11)return;
if(!((byte.toHex().at(0)=='5'&&byte.toHex().at(1)=='a')||(byte.toHex().at(0)=='5'&&byte.toHex().at(1)=='A')))return;
/* QString showstr;
for(int i=0;i<byte.length();i++){
showstr += QString("%1").arg((uchar)byte.at(i),2,16,QLatin1Char('0')).toUpper()+" ";
}*/
/*//*******校验和
QString qdata[11];
int idata[11],sum=0x00;
for(int i=0;i<10;i++){//数据
qdata[i] = qstr.mid(2*i,2);
idata[i] = qdata[i].toInt(&ok,16);
sum += idata[i];
}
qdata[10] = qstr.mid(20,2);//校验和
idata[10] = qdata[10].toInt(&ok,16);
if(sum!=idata[10])return;*/
bool ok;
QString qstr = byte.toHex();
}
4.发送数据
void MainWindow::SendData(){
QByteArray ba;
ba.resize(4);
ba[0]=0x5a;
ba[1]=0x00;
ba[2]=0x00;
ba[3]=ba[0]+ba[1]+ba[2];
serial->write(ba);
}
}