串列埠原始碼(可裁剪)
阿新 • • 發佈:2018-11-09
最近在做一個專案需要使用到串列埠通訊,隨後自己便編寫了一段串列埠程式。
介面如下圖:
原始碼:
serial.pro
#------------------------------------------------- # # Project created by QtCreator 2018-08-24T16:40:35 # #------------------------------------------------- QT += core gui widgets QT += serialport TARGET = serial TEMPLATE = app # The following define makes your compiler emit warnings if you use # any feature of Qt which has been marked as 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 you use 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 CONFIG += c++11 SOURCES += \ main.cpp \ mainwindow.cpp HEADERS += \ mainwindow.h FORMS += \ mainwindow.ui # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target RESOURCES += \ resource.qrc
main.cpp
#include "mainwindow.h" #include <QApplication> #include <QProcess> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); int e = a.exec(); if (e == 777) { QProcess::startDetached(qApp->applicationFilePath(),QStringList()); return 0; } return e; }
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QDebug> #include <QtSerialPort/QSerialPort> #include <QtSerialPort/QSerialPortInfo> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; private slots: void on_OpenSerialButton_clicked(); void ReadData(); void on_SendButton_clicked(); void on_clearButton_clicked(); void on_clearInputButton_clicked(); void on_quitButton_clicked(); private: QSerialPort *serial; QByteArray QString2Hex(QString str); char ConvertHexChar(char ch); }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
this->setWindowFlags(Qt::Dialog);
ui->setupUi(this);
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
QSerialPort serial;
serial.setPort(info);
if (serial.open(QIODevice::ReadWrite))
{
ui->PortBox->addItem(serial.portName());
serial.close();
}
}
ui->BaudBox->setCurrentIndex(1);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_quitButton_clicked()
{
qApp->exit(777);
}
/*
*
* 開啟串列埠槽函式
*
*/
void MainWindow::on_OpenSerialButton_clicked()
{
if (ui->OpenSerialButton->text() == tr("開啟串列埠"))
{
serial = new QSerialPort;
serial->setPortName(ui->PortBox->currentText());
serial->open(QIODevice::ReadWrite);
if (ui->BaudBox->currentIndex() == 0)
serial->setBaudRate(QSerialPort::Baud1200);
else if (ui->BaudBox->currentIndex() == 1)
serial->setBaudRate(QSerialPort::Baud2400);
else if (ui->BaudBox->currentIndex() == 2)
serial->setBaudRate(QSerialPort::Baud4800);
else if (ui->BaudBox->currentIndex() == 3)
serial->setBaudRate(QSerialPort::Baud9600);
else if (ui->BaudBox->currentIndex() == 4)
serial->setBaudRate(QSerialPort::Baud19200);
else if (ui->BaudBox->currentIndex() == 5)
serial->setBaudRate(QSerialPort::Baud38400);
else if (ui->BaudBox->currentIndex() == 6)
serial->setBaudRate(QSerialPort::Baud57600);
else if (ui->BaudBox->currentIndex() == 7)
serial->setBaudRate(QSerialPort::Baud115200);
switch (ui->BitBox->currentIndex())
{
case 8:
serial->setDataBits(QSerialPort::Data8);
break;
default:
break;
}
switch (ui->ParityBox->currentIndex())
{
case 0:
serial->setParity(QSerialPort::NoParity);
break;
default:
break;
}
switch (ui->BitBox->currentIndex())
{
case 1:
serial->setStopBits(QSerialPort::OneStop);
break;
case 2:
serial->setStopBits(QSerialPort::TwoStop);
break;
default:
break;
}
serial->setFlowControl(QSerialPort::NoFlowControl);
ui->PortBox->setEnabled(false);
ui->BaudBox->setEnabled(false);
ui->BitBox->setEnabled(false);
ui->StopBit->setEnabled(false);
ui->ParityBox->setEnabled(false);
ui->OpenSerialButton->setText(tr("關閉串列埠"));
QObject::connect(serial, &QSerialPort::readyRead, this, &MainWindow::ReadData);
}
else
{
serial->clear();
serial->close();
serial->deleteLater();
ui->PortBox->setEnabled(true);
ui->BaudBox->setEnabled(true);
ui->BitBox->setEnabled(true);
ui->StopBit->setEnabled(true);
ui->ParityBox->setEnabled(true);
ui->OpenSerialButton->setText(tr("開啟串列埠"));
}
}
/*
*
* 串列埠讀資料槽函式
*
*/
void MainWindow::ReadData()
{
int bytelen = serial->bytesAvailable();
if (bytelen <= 0)
return;
qDebug("byteLen=%d\n", bytelen);
QByteArray buf = serial->readAll();
if (this->ui->checkBox_2->isChecked())
{
QString temp = buf.toHex().data();
QString temp1;
for (int i=0; i<temp.length()/2; i++)
{
char s = temp.toLatin1().at(i);
if ( s >= 'a' && s <= 'f')
{
s -= 32;
temp1 += s+temp.mid(i*2+1, 1)+" ";
}
else
temp1 += temp.mid(i*2,2)+" ";
}
ui->textEdit->append(temp1);
}
else
ui->textEdit->append(buf);
}
/*
*
* 清空接收區
*
*/
void MainWindow::on_clearButton_clicked()
{
ui->textEdit->clear();
}
/*
*
* 清空輸入區
*
*/
void MainWindow::on_clearInputButton_clicked()
{
ui->textEdit_2->clear();
}
/*
*
* 傳送按鈕槽函式
*
*/
void MainWindow::on_SendButton_clicked()
{
QString str = ui->textEdit_2->toPlainText();
qDebug(str.toLatin1());
QByteArray bytearray;
if (ui->checkBox->isChecked() == true)
{
bytearray = QString2Hex(str);
serial->write(bytearray);
}
else
serial->write(str.toLatin1());
qDebug(str.toLatin1());
}
/*
*
* 將字串轉為16進位制
*
*/
QByteArray MainWindow::QString2Hex(QString str)
{
QByteArray senddata;
qDebug("QString2Hex\n");
int hexdata,lowhexdata;
int hexdatalen = 0;
int len = str.length();
senddata.resize(len/2);
char lstr, hstr;
for (int i=0; i<len;)
{
hstr = str[i].toLatin1();
if (hstr == ' ')
{
i++;
continue;
}
i++;
if (i >= len)
break;
lstr = str[i].toLatin1();
if (hstr >= 'a' && hstr <= 'f')
hstr -= 32;
if (lstr >= 'a' && lstr <= 'f')
lstr -= 32;
hexdata = ConvertHexChar(hstr);
lowhexdata = ConvertHexChar(lstr);
if ((hexdata == 16) || lowhexdata == 16)
break;
else
hexdata = hexdata*16+lowhexdata;
i++;
senddata[hexdatalen] = (char)hexdata;
hexdatalen++;
}
senddata.resize(hexdatalen);
return senddata;
}
/*
*
* 將單個字元轉換成16進位制
*
*/
char MainWindow::ConvertHexChar(char ch)
{
qDebug("ConvertHexChar\n");
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;
}
附錄:串列埠助手.exe
連結地址:https://download.csdn.net/download/qq_16093323/10673157
串列埠助手release版本
連結地址:https://download.csdn.net/download/qq_16093323/10672059