最近刚好用上串口工具就写了一个 自用的 凑合一下,网上的带广告不好用 ,源码在附件
用的Qt自带的QSerialPort以及QSerialPortInfo
代码片段
void MainWindow::initrd(){
/* 串口初始化 */
serialPort = new QSerialPort(this);
ui->comBox->clear();
ui->comBox->addItems( getComNum());
comConfig<<ui->comBox \
<<ui->baundBox \
<<ui->dataBox \
<<ui->stopBox \
<<ui->crcBox \
<<ui->ctrlBox;
ui->comBox->setCurrentIndex(0);
ui->baundBox->setCurrentIndex(6);
ui->dataBox->setCurrentIndex(3);
ui->stopBox->setCurrentIndex(0);
ui->crcBox->setCurrentIndex(0);
ui->ctrlBox->setCurrentIndex(0);
on_comBox_activated(ui->comBox->currentText());
on_baundBox_activated(6);
on_dataBox_activated(3);
on_stopBox_activated(0);
on_crcBox_activated(0);
on_ctrlBox_activated(0);
#if 0
serialPort->setBaudRate(QSerialPort::Baud115200);
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->setParity(QSerialPort::NoParity);
serialPort->setFlowControl(QSerialPort::NoFlowControl);
#endif
/* 接收显示 */
ui->disTextRadio->setChecked(true);
isDisPlay = true;
ui->rcvDisPlay->setReadOnly(true);
/* 日志保存 */
ui->rcvLogFile->setChecked(false);
/* 串口buff初始化 */
comBuff.clear();
/* 初始化串口接收定时器 */
rcvDateTimer = new QTimer(this);
//rcvDateTimer->setInterval(10);
connect(rcvDateTimer, &QTimer::timeout, this, &MainWindow::disPlayLog);
/* 保存日志 */
/* 默认保存在工作目录中 */
/* 默认保存到我的文档目录 */
QString logFilePath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/mycoms/log/";
/* 检测目录是否存在 不存在创建 */
QFileInfo info(logFilePath);
qDebug()<<logFilePath;
if(info.isDir() == false){
QDir dir;
dir.mkpath(logFilePath);
}
logFilePath += QDateTime::currentDateTime().toString("log-yyyy_MM_dd-hh_mm_ss") + ".log";
/* 原始日志 */
logPath = logFilePath;
}
串口获取
QStringList MainWindow::getComNum(){
QStringList comList;
QList<QSerialPortInfo> serialList = QSerialPortInfo::availablePorts();
for(int i= 0; i< serialList.length();i++){
comList<<serialList.at(i).portName();
}
comList.sort();
return comList;
}
串口读取:
void MainWindow::readyRead(){
if( (rcvDateTimer->isActive()) && (rcvDateTimer->interval() > 0)){
rcvDateTimer->stop();
}
QByteArray rcvdata;
QString rcvDis;
rcvdata = serialPort->readAll();
if(ui->disHexRadio->isChecked()){/* hex 显示 */
rcvDis = QString(rcvdata.toHex().toUpper());
QString tmp,disTmp;
for(int i = 0; i< rcvDis.length();i+=2){
tmp.clear();
tmp = rcvDis.mid(i,2);
disTmp += tmp;
disTmp += " ";
}
rcvDis = disTmp;
}else {/* 文本显示 */
rcvDis = QString(rcvdata);
}
comBuff += rcvDis;
rcvDateTimer->start(20);
}
串口发送:
void MainWindow::on_sendBtnTwo_clicked()
{
QByteArray da;
if(serialPort->isOpen() == false){
QMessageBox::information(this, "错误2","请打开串口后发送数据");
return;
}
QString tmp = ui->sendDataTwo->text().simplified().remove(QRegExp("\\s"));
sendPlayLog(tmp);
if(ui->sendHexTwo->isChecked() == true){
/* hex 发送 */
da = QString2Hex(tmp);
}else{
/* 文本发送 */
da = ui->sendDataTwo->text().toLocal8Bit();
}
serialPort->write(da);
sendPlayLog(QString(da));
}
其他部分详见附件:附件
免积分通道
链接: https://pan.baidu.com/s/17hM7y0xw0WFFgPbaC7OjRg 提取码: tnvj