简述
紧接上一次关于Qt5自带的串口库的使用,本次我分享一下Qt的第三方串口库的使用以及一些注意事项。
第三方库的获取
关于第三方串口库的获取可以点击此处下载源码.
解压后的源码文件如下图:
文件调用
本次我使用的是windows平台,故而在项目目录下添加win_qextserialport.cpp/h
、qextserialbase.cpp/h
和qextserialport.cpp/h
6个文件,如果是在Linux平台下则在相应的项目源码路径下添加posix_qextserialport.cpp/h
,区别于windows下的win_qextserialport.cpp/h,其他四个文件相应添加到项目目录下。在编译器里导入工程中,如下图所示:
//Mainwindow.h
#define MAINWINDOW_H
#include "win_qextserialport.h"
#include <QMainWindow>
#include <QEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
myPortInit(void); //串口设置函数
~MainWindow();
private slots:
void readMyCom(); //自定义槽函数,用于读取接收到的数据
void write(); //自定义槽函数,用于发送
private:
Ui::MainWindow *ui;
Win_QextSerialPort *myCom; //定义一个串口对象
};
#endif // MAINWINDOW_H
关键函数实现
void MainWindow::myPortInit(void)
{
//串口号大于10的串口需要使用串口名“\\\\.\\COM11”,否则无法操作串口
myCom = new Win_QextSerialPort("\\\\.\\COM11", QextSerialBase::EventDriven);
//此处须留意,必须先打开串口再设置串口的参数,否则设置的参数无效
if (myCom->open(QIODevice::ReadWrite)){
myCom->setBaudRate(BAUD115200);
myCom->setDataBits( DATA_8);
myCom->setParity(PAR_NONE);
myCom->setStopBits(STOP_1);
myCom->setFlowControl(FLOW_OFF);
myCom->setTimeout(200);
}
}
//串口发送函数
void MainWindow::write(void)
{
QString temp = ui->sendLine->text();
// const char *data;
// qint64 len;
QByteArray ba = temp.toLatin1(); //toASCII()适用在qt4
// data = ba.data();
myCom->write(ba); //直接以字节数组发送
ui->sendLine->clear();
qDebug()<< temp;
}
//串口读取函数
void MainWindow::readMyCom(void)
{
QByteArray temp = myCom->readAll();
ui->textBrowser->insertPlainText(temp);//display datas
}
注意事项
由于该库最初是为了解决在qt4下的串口操作问题,所以直接用在qt5下可能会报一些错误如关于 toAscii() and fromAscii()的错误解决方法是用下面的来代替 :
toLatin1()
fromLatin1()
总结
本文只是简单介绍了第三方库的基本使用,如有错误,欢迎指正。