qt之串口

                                               qt串口讲解
在QT中并没有特定的串口控制类,现在大部分人使用的是第三方写的qextserialport类,我们这里也使用这个类,我们可以去
http://sourceforge.net/projects/qextserialport/files/
进行下载,中国的csdn下载,还要积分,太可恶了!
我们在windows下只需要使用其中的6个文件:
qextserialbase.cpp qextserialbase.h,qextserialport.cpp和qextserialport.h,win_qextserialport.cpp和posix_qextserialport.h即可
linux下只需要将win_qextserialport.cpp和win_qextserialport.h换为posix_qextserialport.cpp和posix_qextseralport即可
第一部分:
  1.打开Qt Creator,新建Qt Gui Application,工程名设置为mycom,其他设置为默认选项。(创建工程使用英文名)
  2.将上面所说的6个文件复制到工程文件夹下
  3.在工程中添加这6个文件
  在Qt Creator中左侧的文件列表中,鼠标右击工程文件就夹,在弹出的菜单中选择Add Existing Files,添加已经存在的文件。选择工程文件夹里的那6个文件,进行添加。
  4.点击mainwindow.ui,在窗口上加入一个Text browser,用来显示信息。
  5.在mainwindow.h的相应位置添加头文件#include "win_qextserialport.h",添加对象声明Win_QextSerialPort *myCom;添加槽函数声明 void readMycom();
  6.在mainwindow.cpp的类的构造函数中添加如下语句
  Mainwindow::MainWindow(QWidget *parent)
  :QMainWindow(parent),ui(new Ui::MainWindow)
  {
  ui->seruoUi(this);
  struct PortSettings myComSetting = {BAUD9600,DATA_8,PAR_NONE,STOP_1,FLOW_OFF,500};
  //定义一个结构体,用来存放串口各参数
  myCom = new Win_QextSerialPort("com1",myComSetting,QextSerialBase::EventDriven);//定义串口对象,并传递参数,在构造函数里对其初始化
  myCom->open(QIODevice:ReadWrite);
  //以读写的方式打开串口
  connect(myCom,SIGNAL(readyread()),this,SLOT(readMyCom()));
  //信号和槽函数关联,当串口缓冲区有数据时,进行读串口的操作
  }
  在下面添加readMyCom()函数的定义,添加如下代码。
  void MainWindow::readMyCom()//读串口函数
  {
  QByteArray temp = myCom->readAll();
  //读取串口缓冲区的所有数据给临时变量temp
  ui->textBrowser->insertPlainText(temp);
  //将串口的数据显示在窗口的文本浏览器中
  }
2.第二部分
  1》首先说明一下串口操作的流程
  1.1:设置串口参数,如:波特率,数据位,奇偶校验位,停止位,数据流控制等。
  1.2:选择串口,如Windows下的串口1为com1,Linux下的串口为ttyS0等,并打开串口。
  1.3:读或写串口
  1.4:关闭串口

3.文件下载:

     Linux下需要的文件:百度云盘:链接:http://pan.baidu.com/s/1nvFC2tN 密码:4ana

     windows下需要的文件:百度云盘:链接:http://pan.baidu.com/s/1c2uqjhm 密码:9mh4

The future's not set,there is no fate but what we make for ourselves.
原文地址:https://www.cnblogs.com/wang1994/p/5943009.html