整理出来自己写的过程中较为纯净版的串口助手,给大家交流学习:http://download.csdn.net/detail/mao19931004/9737142


最近教研室在做高速相机,通过图像采集卡和自己做的高速相机链接,从而采集和收集图像。图像采集卡和高速相机是通过Cameralink连接,其中也包含了相机和图像采集卡之间的串口的硬件借口,在老师的要求下,实现了两种串口程序,一种是通过cameralink的API实现串口数据的传输,一种则是通过USB转RS422的转接器,实现对高速相机的寄存器的读写。本文主要介绍了通过Qt的QSerialPortQSerialPortInfo两个类,实现的串口程序。

本文采用的的开发环境是VS2010+Qt5.5.1版本,所有程序不是通过Qt Creator编译的,如果有需要可以介绍VS2010和Qt环境的搭建和简单的使用

  • QSerialPort

QSerialPort这个类是从QT5.1开始引入的,之前都是通过QIODevice自己定义串口类,从而实现串口程序的开发。现在引入这个类了,将会非常方便的开发串口程序。为了使用这个类,需要在工程目录和附加依赖项中加入include的路径,以及链接库的路径,以及链接库的名称

  • 项目--->属性---> C++ ---> 常规 --->C:\Qt\Qt5.5.1\5.5\msvc2010\include\QtSerialPort
  • 项目--->属性---> 输入++ ---> 附加依赖项--->Qt5SerialPort.lib(如果是Debug版本,则是Qt5SerialPortd.lib)版本
  • 源文件或者头文件需要加入#include<QSerialPort>
串口的信息可以通过QSerialPortInfo类获得,通过这个类,你可以正确的确定你要开启的串口,同时可以获得串口的描述性信息以及厂家信息。串口有三种打开模式,即ReadOnly,WriteOnly,以及ReadWrite。同时可以设置其停止位,波特率,数据位,校验方式以及流控,对应的函数方式分别为:setStopBits(),setBaudRates(),setDataBits(),setParity(),以及setFlowControl()。

串口数据的写入是通过writeData(const char * data, qint64 maxSize)以及write(const char * data, qint64 maxSize),前者是protected属性,只能在子类中访问,而后者则是public属性。在串口打开并且具有可写属性,即可通过write函数写入数据。

串口数据的读入是通过readData(char * data, qint64 maxSize) ,read(qint64 maxSize)实现的,如果需要一次性读完所有的数据,则可以通过readAll()全部读取串口缓冲区中的数据。

串口内部的缓冲区大小可以通过:setReadBufferSize(qint64 size)实现。当设定缓冲区大小时,串口只能接收size大小的数据流,因此存在数据丢书的可能。当设置为0的时候,并不是指的缓冲区大小为0,而是无穷大,这样就可以保存数据的全部接收完整。这是缓冲区大小的默认属性。

是否有新的数据读入缓冲区是通过readReady()信号来来确定的。这是通过时间驱动的方式来确定是否有数据可以读入。此外还有waitForReadyRead()来等待轮询是否有数据到达串口,但是这是一种阻塞性读入,个人觉得不是太好,所以写串口的时候采用的是事件驱动的方式来确定是够有数据可以读入。

  • QSerialPortInfo

可能会用得比较多的函数是description(),manufacturer(),以及serialNumber()。从而得到描述性信息,比如通信端口。USB转串口等描述串口的信息、串口的

生产商信息以及串口名,在电脑上表现为COM~等。

  • 如何获取电脑上所有的串口

[cpp] view plain copy
 print?
  1. void CameraSerialPort::getSerialPortID()  
  2. {  
  3.      serialInfo=new QSerialPortInfo();  
  4.      serialList=serialInfo->availablePorts();  
  5.     int nSerialnum=serialList.length();  
  6.     for(int i=0;i<nSerialnum;i++)  
  7.     {  
  8.         QString serialName=serialList[i].portName();  
  9.         QString serialDesp=serialList[i].description();  
  10.         serialPortAssitant.serialPortcomboBox->addItem(serialName);  
  11.     }  
  12.       
  13.     QString currentPort=serialPortAssitant.serialPortcomboBox->currentText();  
  14.     portToOpen=currentPort;  
  15.     QString  portStatus=currentPort+" closed";  
  16.     serialPortAssitant.status->statusInfo->setText(portStatus.toUpper());  
  17.     QPalette font_palette;  
  18.     font_palette.setColor(QPalette::WindowText,Qt::red);  
  19.     serialPortAssitant.status->statusInfo->setPalette(font_palette);  
  20. }  
因为直接从自己的项目文件拷过来的源码,这里稍微介绍一下属性:

1、变量的定义,在头文件中,这里没有贴出来,截取定义如下:

[cpp] view plain copy
 print?
  1. QSerialPortInfo* serialInfo;  
  2. QList<QSerialPortInfo>serialList;  
2、QList<QSerialPortInfo>availablePorts() 返回的是一个关于QSerialPortInfo的列表,在数据结构QList中存储。

3、serialPortcomBox是一个QComboBox,下拉列表。

4、最后几行是用来显示串口的状态信息,达到的效果如图:

Qt -- Qt5.5.1实现通用串口程序


  • 打开串口并且通过串口写数据

得到串口信息后,就可以选择端口,进行打开和读写数据。贴出代码,然后在给分析分析:

[cpp] view plain copy
 print?
  1. void CameraSerialPort::Write()  
  2. {  
  3.     QString sendMsg=serialPortAssitant.sendLine->text();  
  4.     QByteArray temp=sendMsg.toLatin1();  
  5.     if(IsSendByHex)  
  6.     {  
  7.         temp=HexStrToByteArray(sendMsg);  
  8.     }  
  9.     char *sendContent=temp.data();  
  10.     qint64 sendedNum=serialPort->write(sendContent,temp.count());  
  11.   
  12.     //---------------判断发送数据是否成功----------------------//  
  13.     if(sendedNum==-1)  
  14.     {  
  15.         errorValue=serialPort->error();  
  16.         if(IsShowCurrentTime)  
  17.         {  
  18.             errorInfo=" ";  
  19.             currentTime=QDateTime::currentDateTime();  
  20.             timeinfo=currentTime.toString("yyyy__MM__d__hh:mm:ss");  
  21.             errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  22.             errorInfo+=timeinfo;  
  23.             errorInfo+="\n";  
  24.         }  
  25.         else  
  26.         {  
  27.             errorInfo=" ";  
  28.             errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  29.             errorInfo+="\n";  
  30.         }  
  31.         serialPortAssitant.ReciveWidget->append(errorInfo+getValueContent(errorValue));  
  32.         return;  
  33.     }  
  34.     //-------------显示发送数据-----------------------//  
  35.   
  36.     //temp的size的依据是是否以16进制发送  
  37.     sendCount+=temp.count();  
  38.     serialPortAssitant.status->TxByte->setText(QString::number(sendCount));  
  39.     QString showSendMsg;  
  40.     if(IsShowSendMsg)  
  41.     {  
  42.         if(IsShowCurrentTime)  
  43.         {  
  44.   
  45.             currentTime=QDateTime::currentDateTime();  
  46.             timeinfo=currentTime.toString("yyyy__MM__d__hh:mm:ss");  
  47.             showSendMsg+=QString::fromLocal8Bit("发送数据 : ");  
  48.             showSendMsg+=timeinfo;  
  49.             showSendMsg+="\n";  
  50.             //判断显示16进制还是ACSII字符  
  51.             if(IsSendByHex)  
  52.                 showSendMsg+=ByteArrayToHexStr(temp);  
  53.             else  
  54.                 showSendMsg+=temp;  
  55.         }     
  56.         else  
  57.         {  
  58.             showSendMsg=QString::fromLocal8Bit("发送数据 : ");  
  59.             if(IsSendByHex)  
  60.                 showSendMsg+=ByteArrayToHexStr(temp);  
  61.             else  
  62.                 showSendMsg+=temp;  
  63.               
  64.         }     
  65.         serialPortAssitant.ReciveWidget->append(showSendMsg);  
  66.   
  67.     }     
  68.     IsWrittenSuccessed=true;  
  69. }  

[cpp] view plain copy
 print?
  1. void CameraSerialPort::sendData()  
  2. {  
  3.     if(!IsSerialPortOpen)  
  4.     {  
  5.             if(serialPort!=NULL)  
  6.             {  
  7.                 serialPort->close();  
  8.             }  
  9.             serialPort=new QSerialPort(portToOpen);  
  10.             if(serialPort==NULL)  
  11.             {  
  12.                 errorValue=serialPort->error();  
  13.                 QString errorContent=getValueContent(errorValue);  
  14.                 if(IsShowCurrentTime)  
  15.                 {  
  16.                         errorInfo=" ";  
  17.                         currentTime=QDateTime::currentDateTime();  
  18.                         timeinfo=currentTime.toString("yyyy__MM__d__hh:mm:ss");  
  19.                         errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  20.                         errorInfo+=timeinfo;  
  21.                         errorInfo+="\n";  
  22.                 }  
  23.                     else  
  24.                 {  
  25.                         errorInfo=" ";  
  26.                         errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  27.                         errorInfo+="\n";  
  28.                 }  
  29.                     serialPortAssitant.ReciveWidget->append(errorInfo +errorContent+QString::fromLocal8Bit(", 请重新选择正确的端口\n"));  
  30.                     return;       
  31.             }  
  32.   
  33.         if(!serialPort->open(QIODevice::ReadWrite))  
  34.         {  
  35.             errorValue=serialPort->error();  
  36.             QString errorContent=getValueContent(errorValue);  
  37.             if(IsShowCurrentTime)  
  38.             {  
  39.                 errorInfo=" ";  
  40.                 currentTime=QDateTime::currentDateTime();  
  41.                 timeinfo=currentTime.toString("yyyy__MM__d__hh:mm:ss");  
  42.                 errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  43.                 errorInfo+=timeinfo;  
  44.                 errorInfo+="\n";  
  45.             }  
  46.             else  
  47.             {  
  48.                 errorInfo=" ";  
  49.                 errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  50.                 errorInfo+="\n";  
  51.             }  
  52.             serialPortAssitant.ReciveWidget->append(errorInfo +errorContent);  
  53.             return;       
  54.         }  
  55.         <span style="background-color: rgb(255, 0, 0);">connect(serialPort,SIGNAL(readyRead()),this,SLOT(onReadyRead()));</span>  
  56.         serialPort->setDataBits(QSerialPort::Data8);  
  57.         serialPort->setStopBits(QSerialPort::OneStop);  
  58.         serialPort->setParity(QSerialPort::NoParity);  
  59.         serialPort->setFlowControl(QSerialPort::NoFlowControl);  
  60.   
  61.         QString serialStatusInfo;  
  62.         serialStatusInfo=serialPortAssitant.serialPortcomboBox->currentText().toUpper();  
  63.         serialStatusInfo+=" OPENED";  
  64.         serialStatusInfo+=" , ";  
  65.         serialStatusInfo+=QString::number(serialPort->baudRate());  
  66.         serialStatusInfo+=" , ";  
  67.         serialStatusInfo+=serialPortAssitant.DataWidthcomboBox->currentText();  
  68.         serialStatusInfo+=" , ";  
  69.         serialStatusInfo+=serialPortAssitant.ParityWidthcomboBox->currentText().toUpper();  
  70.         serialStatusInfo+=" , ";  
  71.         serialStatusInfo+=serialPortAssitant.StopWidthcomboBox->currentText();  
  72.         serialStatusInfo+=" , ";  
  73.         serialStatusInfo+=serialPortAssitant.FLowControlcomboBox->currentText().toUpper();  
  74.         QPalette font_palette;  
  75.         font_palette.setColor(QPalette::WindowText,Qt::darkCyan);  
  76.         serialPortAssitant.status->statusInfo->setText(serialStatusInfo);  
  77.         serialPortAssitant.status->statusInfo->setPalette(font_palette);  
  78.   
  79.         serialPortAssitant.sendBtn->setText(QString::fromLocal8Bit("发送"));  
  80.         IsSerialPortOpen=true;  
  81.     }  
  82.   
  83. else  
  84.     {  
  85.         if(IsRepeatSend)  
  86.         {  
  87.             repeatSend->start();  
  88.         }  
  89.         Write();  
  90.     }  
  91. }  

首先看write函数:以下是从write函数中抽离出来的几行关键代码:

[cpp] view plain copy
 print?
  1.  <span style="white-space:pre">   </span>QString sendMsg=serialPortAssitant.sendLine->text();  
  2. lt;span style="white-space:pre"> </span>QByteArray temp=sendMsg.toLatin1();  
  3. char *sendContent=temp.data();  
  4. qint64 sendedNum=serialPort->write(sendContent,temp.count());  
 1、第一行是从QLineEdit获取需要发送的数据信息;

 2、第二行到第三行代码是需要把QString转换为char *的数据类型。

 3、第四行则是通过QIODevice类的成员函数write写出数据。

 4、剩余的部分是一些细节的错误提示显示以及显示信息,以及非常重要的是以ASCII形式发出数据还是以16进制发送数据。


接着是sendData()函数。

[cpp] view plain copy
 print?
  1. serialPort=new QSerialPort(portToOpen);  
  2. if(!serialPort->open(QIODevice::ReadWrite))  
  3. connect(serialPort,SIGNAL(readyRead()),this,SLOT(onReadyRead()));  

1、第一行是通过portToOpen实例化QSerialPort,构造函数为:QSerialPort(const QString & name, QObject * parent = Q_NULLPTR)

 2、第二行是打开串口,打开模式是ReadWrite,可写可读

3、第三行是通过readRead()信号来实现串口数据的读出,事件驱动的方式。这一行我在源代码中加了红色,原因是,一定要在打开串口后,实现readyRead()信号和对应的槽函数的连接,如果在没有初始化串口成功后,然后信号才能启动。我最开始在CameraSerialPort这个类的初始化中就定义了这个信号槽的链接,一直没有读到串口数据,结果在网上找了半天的原因,也没有找到这个问题。想了一下,然后把代码移到了这里,就可以了

打开串口和发送数据的结果如图:

Qt -- Qt5.5.1实现通用串口程序

Qt -- Qt5.5.1实现通用串口程序

  • 串口接收数据

[cpp] view plain copy
 print?
  1. void CameraSerialPort::Read()  
  2. {  
  3.     if(serialPort->bytesAvailable()<0)  
  4.     {  
  5.         serialPortAssitant.ReciveWidget->setText("No data");  
  6.         return;  
  7.     }     
  8.   
  9.       
  10.       
  11.     QByteArray temp;  
  12.     temp=serialPort->readAll();  
  13.   
  14.     QString  receiveMsg;  
  15.     if(IsReceiveByHex)  
  16.         receiveMsg=ByteArrayToHexStr(temp);  
  17.     else   
  18.         receiveMsg=temp;  
  19.       
  20.     if(receiveMsg.isEmpty())  
  21.     {  
  22.         if(IsShowCurrentTime)  
  23.         {  
  24.             errorInfo=" ";  
  25.             currentTime=QDateTime::currentDateTime();  
  26.             timeinfo=currentTime.toString("yyyy__MM__d__hh:mm:ss");  
  27.             errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  28.             errorInfo+=timeinfo;  
  29.             errorInfo+="\n";  
  30.         }  
  31.         else  
  32.         {  
  33.             errorInfo=" ";  
  34.             errorInfo=QString::fromLocal8Bit("错误提示信息   ");  
  35.             errorInfo+="\n";  
  36.         }  
  37.         serialPortAssitant.ReciveWidget->append(errorInfo +QString::fromLocal8Bit("没有读到数据\n"));  
  38.         return;  
  39.     }  
  40.   
  41.     //接收到的字节数以初始的bytes为依据  
  42.     reciveCount+=temp.count();  
  43.     serialPortAssitant.status->RxByte->setText(QString::number(reciveCount));  
  44.     QString showReciveMsg;  
  45.     if(IsShowCurrentTime)  
  46.         {  
  47.   
  48.             currentTime=QDateTime::currentDateTime();  
  49.             timeinfo=currentTime.toString("yyyy__MM__d__hh:mm:ss");  
  50.             showReciveMsg+=QString::fromLocal8Bit("接收数据 : ");  
  51.             showReciveMsg+=timeinfo;  
  52.             showReciveMsg+="\n";  
  53.             showReciveMsg+=receiveMsg;  
  54.         }     
  55.         else  
  56.         {  
  57.             showReciveMsg=QString::fromLocal8Bit("接收数据 : ");  
  58.             showReciveMsg+=receiveMsg;  
  59.         }     
  60.         serialPortAssitant.ReciveWidget->append(showReciveMsg);  
  61.   
  62. }  
  63.   
  64. void CameraSerialPort::onReadyRead()  
  65. {  
  66.     Read();  
  67. }  

1、读入数据之前,需要判断缓冲区是否有数据,有数据才去读数据

2、如果有数据,则全部读出缓冲区数据

  • 总结

大致的有关Qt的串口类就介绍完了,主要是QSerialPort以及QSerialPortInfo两个类的使用,当然也需要了解QIODevice。

相关文章: